<?php
namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\LogPackageContentModel;
use App\V3\V3_2_7\Models\LogPackageModel;
use App\V3\V3_2_7\Models\MaterielsTypeModel;
use App\V3\V3_2_7\Models\PackageContentModel;
use App\V3\V3_2_7\Models\PackageModel;
use App\V3\V3_2_7\Models\ProductSlaveContentStorageModel;
use App\V3\V3_2_7\Models\SalesReturnInPackageContentModel;
use App\V3\V3_2_7\Models\SalesReturnInPackageModel;
use App\V3\V3_2_7\Models\SalesReturnInStorageModel;
use App\V3\V3_2_7\Models\SalesReturnPackageContentModel;
use App\V3\V3_2_7\Models\SalesReturnPackageModel;
use App\V3\V3_2_7\Models\SerialNumberModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use App\V3\V3_2_7\Models\SalesReturnGoodsDetailModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\SalesReturnPayRecordModel;
use App\V3\V3_2_7\Services\StorageManageService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\V3\V3_2_7\Models\SalesReturnGoodsBatchModel;
use App\V3\V3_2_7\Models\SalesReturnPackageBatchModel;
use App\V3\V3_2_7\Models\StorageBatchModel;
use App\V3\V3_2_7\Models\SalesOutSerialNumberModel;
use App\V3\V3_2_7\Models\SalesReturnPackageSerialNumberModel;
use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use App\V3\V3_2_7\Models\SellModel;

class SalesReturnService
{
    static public function sellAddBatch($data)
    {
        DB::beginTransaction();

        try {
            $info = json_decode($data['info'], true);

            if($data['type'] == 0) {
                $goodsDetialInfo = SalesReturnGoodsDetailModel::where([
                    'id' => $data['id'],
                    'return_id' => $data['return_id']
                ])
                    ->first();

                $totalNum = 0;

                $batchId = [];
                foreach($info as $value) {
                    $batchId[] = $value['batch_id'];
                    $totalNum += $value['num'];
                }

                $goodsDetailBatchInfo =  SalesReturnGoodsBatchModel::select(
                    DB::raw('SUM(rest_num) as total_rest_num')
                )
                    ->where([
                        'return_goods_detail_id' => $data['id'],
                        'return_id' => $data['return_id']
                    ])
                    ->whereIn('storage_batch_id', $batchId)
                    ->first();

                if(($goodsDetialInfo['num'] - $goodsDetialInfo['out_num']) < ($goodsDetailBatchInfo['total_rest_num'] + $totalNum)) {
                    return ['code' => 1, 'msg' => '当前商品批次总数超出商品所需数量，无法设置，请重试', 'data' => ''];
                }

                if(empty($goodsDetailBatchInfo['total_rest_num'])) {
                    foreach($info as $val) {
                        SalesReturnGoodsBatchModel::insert([
                            'storage_batch_id' => $val['batch_id'],
                            'return_goods_detail_id' => $data['id'],
                            'storage_manage_id' => $val['storage_manage_id'],
                            'return_id' => $data['return_id'],
                            'main_id' => $data['main_id'],
                            'num' => $val['num'],
                            'rest_num' => $val['num'],
                            'created_at' => time()
                        ]);
                    }
                }
                else {
                    foreach($info as $v) {
                        $goodsDetailBatchInfos = SalesReturnGoodsBatchModel::where([
                            'return_goods_detail_id' => $data['id'],
                            'storage_batch_id' => $v['batch_id'],
                            'return_id' => $data['return_id']
                        ])
                            ->first();

                        SalesReturnGoodsBatchModel::where('id', $goodsDetailBatchInfos['id'])
                            ->update([
                                'num' => DB::raw("num + " . $v['num']),
                                'rest_num' => DB::raw("rest_num + " . $v['num'])
                            ]);
                    }
                }
            }
            else {
                $packageContentInfo = SalesReturnPackageContentModel::where([
                    'id' => $data['id'],
                    'return_id' => $data['return_id']
                ])->first()->toArray();

                $totalNum = 0;
                $batchId = [];
                foreach($info as $value) {
                    $batchId[] = $value['batch_id'];
                    $totalNum += $value['num'];
                }

                $totalRestNum = SalesReturnPackageBatchModel::select(
                    DB::raw('SUM(rest_num) as total_rest_num')
                )
                    ->where([
                        'return_package_content_id' => $data['id'],
                        'return_id' => $data['return_id']
                    ])
                    ->whereIn('storage_batch_id', $batchId)
                    ->first();


                if(($totalRestNum['total_rest_num'] + $totalNum) > $packageContentInfo['num']) {
                    throw new \Exception('单个商品批次数量超出套餐内商品所需数量');
                }

                if(empty($totalRestNum['total_rest_num'])) {
                    foreach($info as $val) {
                        SalesReturnPackageBatchModel::insert([
                            'return_package_content_id' => $data['id'],
                            'storage_manage_id' => $val['storage_manage_id'],
                            'storage_batch_id' => $val['batch_id'],
                            'return_id' => $data['return_id'],
                            'main_id' => $data['main_id'],
                            'num' => $val['num'],
                            'rest_num' => $val['num'],
                            'created_at' => time()
                        ]);
                    }
                }
                else {
                    foreach($info as $v) {
                        $contentBatchInfo = SalesReturnPackageBatchModel::where([
                            'return_package_content_id' => $data['id'],
                            'storage_batch_id' => $v['batch_id'],
                            'return_id' => $data['return_id']
                        ])
                            ->first();

                        SalesReturnPackageBatchModel::where('id', $contentBatchInfo['id'])
                            ->update([
                                'num' => DB::raw("num + ".$v['num']),
                                'rest_num' => DB::raw("rest_num + ".$v['num'])
                            ]);
                    }
                }
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('添加批次号异常'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }
    //新建
    static public function add($mainInfo, $data)
    {
        DB::beginTransaction();
        if(!empty($data['sell_id'])) {
            $sellInfo = SellModel::where(['id'=>$data['sell_id']])->first();

            if($sellInfo['out_status'] != 2){
                return ['code'=>1,'msg'=>'销售单号：'.$sellInfo['order_no'].'，还没有全部出库，不能生成退货订单！','data'=>''];
            }
        }

        $mainId = SalesReturnModel::insertGetId($mainInfo);//创建销售主单信息
        $return_id = $mainId;
        $money = 0;//货款金额
        try {
            $salesMaterielInfo = [];
            $salesPackageInfo = [];

            if(!empty($data['goods_info'])) {
                $goodsInfo = json_decode($data['goods_info'],true);//商品详细添加

                foreach ($goodsInfo as $key => $value) {

                    if(empty($value['shelf_id']) || empty($value['location_id'])){
                        $sfData = ShelfService::get_default($value['warehouse_id']);
                        if(!empty($sfData)){
                            $shelf_id = $sfData['id'];
                            $lData = ShelfService::get_default($shelf_id,2);
                            $location_id = $lData['id'];
                        }else{
                            $shelf_id = 0;
                            $location_id = 0;
                            $value['shelf_id']=0;
                            $value['location_id']=0;
                        }
                    }else{
                        $shelf_id = $value['shelf_id'];
                        $location_id = $value['location_id'];
                    }
                    $materielInfo  = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();

                    if(!empty($data['sell_id'])){//如果是销售单生成的退货单，算出可退货数量
                        $returnData = SalesReturnModel::select(DB::raw('SUM(num) as total_return_num'))
                            ->from('sales_return as a')
                            ->leftJoin('sales_return_goods_detail as b','b.return_id','=','a.id')
                            ->where(['sell_id' => $data['sell_id'],'b.materiel_type_id' => $value['materiel_type_id']])
                            ->where(['repeal_status' => 0,'delete_flag' => 0])->first()->toArray();

                        if(!empty($returnData)){

                            if($returnData['total_return_num'] >= $value['num']){

                                return ['code'=>1,'msg'=>'组件套餐'.$materielInfo['materiel_name'].'的销售数量已退货完！','data'=>''];

                            }

                            $remaining_num = $value['num'] - $returnData['total_return_num'];//销售数量还剩多少可退数量

                            if(!empty($value['return_num'])){
                                if($value['return_num'] > $remaining_num){
                                    return ['code'=>1,'msg'=>'商品:'.$materielInfo['materiel_name'].'的退货数量超过了剩余数量！可退货数量为：'.$remaining_num,'data'=>''];
                                }
                            }
                        }
                        $value['num'] = $value['return_num'];
                    }
                    $money+=($value['price']*$value['num']);
                    $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();
                    $salesMaterielInfo[$key]['materiel_type_id'] = $value['materiel_type_id'];
//                    $salesMaterielInfo[$key]['remark'] = $value['remark'];
                    $salesMaterielInfo[$key]['name'] = $materielInfo['materiel_name'];
                    $salesMaterielInfo[$key]['type_name'] = $materielInfo['type_name'];
                    $salesMaterielInfo[$key]['price'] = $value['price'];
                    $salesMaterielInfo[$key]['cost_price'] = $materielInfo['cost'];
                    $salesMaterielInfo[$key]['return_id'] = $mainId;
                    $salesMaterielInfo[$key]['num'] = $value['num'];
                    $salesMaterielInfo[$key]['image'] = $materielInfo['materiel_img'];
                    $salesMaterielInfo[$key]['warehouse_id'] = $storageInfo['id'];
                    $salesMaterielInfo[$key]['warehouse'] = $storageInfo['storage_name'];
                    $salesMaterielInfo[$key]['main_id'] = $data['main_id'];
                    $salesMaterielInfo[$key]['created_at'] = time();
                    $salesMaterielInfo[$key]['shelf_id'] = $shelf_id;
                    $salesMaterielInfo[$key]['location_id'] = $location_id;
                }
                SalesReturnGoodsDetailModel::insert($salesMaterielInfo);
            }

            if(!empty($data['package_info'])) {

                $packageInfo = json_decode($data['package_info'],true);//套餐信息
                foreach ($packageInfo as $k => $vals) {
                    $money+=($vals['price']*$vals['num']);
                    $salesPackageInfo[$k]['package_id'] = $vals['package_id'];
                    $salesPackageInfo[$k]['price'] = $vals['price'];
                    $salesPackageInfo[$k]['cost_price'] = self::getPackageCost($vals['package_id']);
                    $salesPackageInfo[$k]['num'] = $vals['num'];
                    $salesPackageInfo[$k]['main_id'] = $data['main_id'];
                    $salesPackageInfo[$k]['return_id'] = $mainId;
//                    $salesPackageInfo[$k]['remark'] = $vals['remark'];
                    $salesPackageInfo[$k]['created_at'] = time();
                    $salesPackageInfo[$k]['package_content'] = $vals['package_content'];
                }

                $packageContentInfo = [];
                foreach($salesPackageInfo as $val) {
                    $newId = SalesReturnPackageModel::insertGetId([
                        'package_id' => $val['package_id'],
                        'price' => $val['price'],
                        'cost_price' => $val['cost_price'],
                        'num' => $val['num'],
                        'main_id' => $val['main_id'],
                        'return_id' => $val['return_id'],
//                        'remark' => $val['remark'],
                        'created_at' => time()
                    ]);

                    foreach($val['package_content'] as $v) {
                        if(empty($v['shelf_id']) || empty($v['location_id'])){
                            /* $shelf_id = ShelfService::get_default($v['storage_id'])['id'];
                            $location_id = ShelfService::get_default($shelf_id,2)['id']; */

                            $sfData = ShelfService::get_default($v['storage_id']);
                            if(!empty($sfData)){
                                $shelf_id = $sfData['id'];
                                $lData = ShelfService::get_default($shelf_id,2);
                                $location_id = $lData['id'];
                            }else{
                                $shelf_id = 0;
                                $location_id = 0;
                                $v['shelf_id']=0;
                                $v['location_id']=0;
                            }
                        }else{
                            $shelf_id = $v['shelf_id'];
                            $location_id = $v['location_id'];
                        }
                        $packageContentInfo[] = [
                            'type_id' => $v['type_id'],
                            'storage_id' => $v['storage_id'],
                            'package_content_id' => $v['id'],
                            'storage_manage_id' => $v['storage_manage_id'],
                            'return_package_id' => $newId,
                            'package_id' => $val['package_id'],
                            'num' => $v['num'],
                            'main_id' => $data['main_id'],
                            'return_id' => $mainId,
                            'created_at' => time(),
                            'shelf_id' => $shelf_id,
                            'location_id' => $location_id,
                        ];
                    }
                }

                SalesReturnPackageContentModel::insert($packageContentInfo);
            }

            //非改价计算价格
            if(!$data['is_zero_suppression'] && $money){
                $finalMoney = 0;
                if(isset($data['discount']) && $data['discount']){//折扣
                    $finalMoney+= ($data['discount']*$money/100);
                }else{
                    $finalMoney = $money;
                }

                if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                    $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                }
                SalesReturnModel::where('id',$mainId)->update(['final_money'=>$finalMoney,'money'=>$money]);
            }else{
                SalesReturnModel::where('id',$mainId)->update(['money'=>$money]);
            }
            $logData = '退货单号：'.$mainInfo['order_no'].'创建成功!';
            CommonService::log('添加退货单', $mainInfo, $logData);
            DB::commit();//提交事务
            return ['code' => 0, 'msg' => 'success', 'data' => $mainId];
        }
        catch(\Exception $e) {
            DB::rollBack();//事务回滚
            Log::debug('添加退货单'.var_export($e->getMessage(), true));
            //异常响应
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    //获取套餐总成本
    static private function getPackageCost($packageId)
    {
        $packageTotalCost = PackageContentModel::select(
            'a.num',
            'b.materiel_mean_cost'
        )
            ->from('package_content as a')
            ->leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
            ->where('a.package_id', $packageId)
            ->where('a.delete_flag', 0)
            ->where('b.delete_flag', 0)
            ->first();

        return $packageTotalCost['num'] * $packageTotalCost['materiel_mean_cost'];
    }

    //详细
    static public function find($id)
    {
        $result = SalesReturnModel::select('a.*','b.username',
            'b.nickname'
        )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('returnMateriel')
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.*',
                    'b.package_name'
                )
                    ->with('packageContent',function($query) {
                        $query->select(
                            'sales_return_package_content.*',
                            'a.materiel_name',
                            'a.type_name',
                            'b.storage_name',
                            'b.storage_address',
                            'c.in_storage_num',
                            'a.materiel_no',
                            'd.id as materiel_class_id',
                            'd.class_name',
                            'a.is_use_serial',
                            'a.materiel_img',
                            'a.selling_price',
                            'e.shelf_name',
                            'f.location_name'
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('storage as b', 'b.id', '=', 'sales_return_package_content.storage_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('materiel_class as d', 'd.id', '=', 'a.materiel_class_id')
                            ->leftJoin('storage_shelf as e','e.id','=','sales_return_package_content.shelf_id')
                            ->leftJoin('storage_shelf_location as f','f.id','=','sales_return_package_content.location_id');
                    })
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id');
            })
            ->where('a.id', $id)->first()->toArray();

        foreach($result['return_materiel'] as &$value) {

            $materielInfo = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();

            $storageManageInfo = StorageManageModel::where('type_id', $value['materiel_type_id'])
                ->where('storage_id', $value['warehouse_id'])->first();

            $value['storage_manage_id'] = $storageManageInfo['id'];
            $value['materiel_class_id'] = $storageManageInfo['materiel_class_id'];
            $value['in_storage_num'] = $storageManageInfo['in_storage_num'];

            $value['image'] = $materielInfo['materiel_img'];
            $value['materiel_no'] = $materielInfo['materiel_no'];

            $shelfInfo = StorageShelfModel::find($value['shelf_id']);
            $locationInfo = StorageShelfLocationModel::find($value['location_id']);
            $value['shelf_name'] = $shelfInfo['shelf_name'];
            $value['location_name'] = $locationInfo['location_name'];
            $value['is_product_materiel'] = $materielInfo['is_product_materiel'];
            if(empty($materielInfo['is_use_serial'])){
                $value['is_use_serial'] = 0;
                $value['serial_number_list'] = [];
            }else{
                $value['is_use_serial']   = $materielInfo['is_use_serial'];
                $scondition['type_id']   = $value['materiel_type_id'];
                $scondition['return_id']  = $id;
                $number_info = SalesOutSerialNumberModel::select('serial_number')->where($scondition)->where('status',1)->get()->toArray();
                $number_list = [];
                if(!empty($number_info)){

                    foreach ($number_info as $sVal){

                        $number_list[]= $sVal['serial_number'];
                    }
                }

                $value['serial_number_list']  = $number_list;
            }
            $bcondition['return_id']= $value['return_id'];
            $bcondition['return_goods_detail_id'] = $value['id'];
            $goodsBatchList = SalesReturnGoodsBatchModel::select('b.batch_no','a.*')
                ->from('sales_return_goods_batch as a')
                ->leftJoin('storage_batch as b','b.id','=','a.storage_batch_id')
                ->where($bcondition)->get()->toArray();
            if(empty($goodsBatchList)) $goodsBatchList=[];
            $value['goods_batch_list'] = $goodsBatchList;
            $value['content']=[];
            if($materielInfo['is_product_materiel'] == 1){//查询是否是组件商品
                $productData = MaterielProductContentModel::select(
                    'a.id',
                    'a.type_id',
                    'b.materiel_name',
                    'b.type_name',
                    'b.materiel_img',
                    'b.materiel_no',
                    'product_id',
                    'a.num',
                    'a.price',
                    'a.total_price'
                )->from('materiel_product_content as a')
                    ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                    ->where('product_id',$value['materiel_type_id'])->where('b.delete_flag',0)->get()->toArray();

                if(!empty($productData)){
                    foreach ($productData as $pk=>$pv){
                        $productSerialNumber = SalesOutSerialNumberModel::select('serial_number')
                            ->where(['return_id'=>$id,'type_id'=>$pv['type_id']])->where('status',1)->get();
                        $pnumber_list = [];
                        if(!empty($productSerialNumber)){
                            foreach ($productSerialNumber as $pVal){

                                $pnumber_list[]= $pVal['serial_number'];
                            }
                        }
                        $productData[$pk]['serial_number_list'] = !empty($pnumber_list) ? $pnumber_list:[];
                        $productData[$pk]['product_batch_list'] = [];
                    }
                    $value['content'] = $productData;
                    $value['is_use_serial']   = $materielInfo['is_use_serial'];
                    $value['serial_number_list']  = [];
                }
            }
        }

        if(!empty($result['return_package'])){
            foreach ($result['return_package'] as $pk=>$pv){
                if(!empty($pv['package_content'])){
                    foreach ($pv['package_content'] as $ck=>$cv){
                        if(empty($cv['is_use_serial'])){
                            $result['return_package'][$pk]['package_content'][$ck]['is_use_serial'] = 0;
                            $result['return_package'][$pk]['package_content'][$ck]['serial_number_list'] = [];
                        }else{
                            $result['return_package'][$pk]['package_content'][$ck]['is_use_serial']  = $cv['is_use_serial'];
                            $scondition['return_package_content_id']   = $cv['id'];
                            $scondition['type_id']   = $cv['type_id'];
                            $scondition['return_id']  = $id;

                            $number_info = SalesReturnPackageSerialNumberModel::select('serial_number')->where($scondition)->where('status',1)->first();

                            if(empty($number_info)){
                                $number_info = [];
                            }else{
                                $number_info=explode(',', $number_info['serial_number']);
                            }
                            $result['return_package'][$pk]['package_content'][$ck]['serial_number_list'] = $number_info;

                        }
                        $ccondition['return_package_content_id']=$cv['id'];
                        $ccondition['return_id']=$pv['return_id'];
                        $batchList = SalesReturnPackageBatchModel::
                        select('b.batch_no','a.*')
                            ->from('sales_return_package_batch as a')
                            ->leftJoin('storage_batch as b','b.id','=','a.storage_batch_id')
                            ->where($ccondition)->get()->toArray();
                        if(empty($batchList)) $batchList=[];
                        $result['return_package'][$pk]['package_content'][$ck]['goods_batch_list']=$batchList;
                    }
                }
            }
        }

        return ['code' => 0, 'msg' => 'success','data' => $result];
    }

    //编辑
    static public function edit($mainInfo, $data)
    {
//        if (isset($mainInfo['refund_date'])) $mainInfo['refund_date'] = strtotime($data['refund_date']);

        $money = 0;

        DB::beginTransaction();

        try {
            if(!empty($data['goods_info'])) {
                SalesReturnGoodsDetailModel::where('return_id', $data['id'])->delete();
                $goodsInfo = json_decode($data['goods_info'], true);

                foreach ($goodsInfo as $key => $value) {

                    if(empty($value['shelf_id']) || empty($value['location_id'])){
                        /* $shelf_id = ShelfService::get_default($value['warehouse_id'])['id'];
                        $location_id = ShelfService::get_default($shelf_id,2)['id']; */
                        $sfData = ShelfService::get_default($value['warehouse_id']);
                        if(!empty($sfData)){
                            $shelf_id = $sfData['id'];
                            $lData = ShelfService::get_default($shelf_id,2);
                            $location_id = $lData['id'];
                        }else{
                            $shelf_id = 0;
                            $location_id = 0;
                            $value['shelf_id']=0;
                            $value['location_id']=0;
                        }
                    }else{
                        $shelf_id = $value['shelf_id'];
                        $location_id = $value['location_id'];
                    }
                    $materielInfo  = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();
                    if(!empty($value['sell_id'])){//如果是销售单生成的退货单，算出可退货数量
                        $returnData = SalesReturnModel::select(DB::raw('SUM(num) as total_return_num'))
                            ->from('sales_return as a')
                            ->leftJoin('sales_return_goods_detail as b','b.return_id','=','a.id')
                            ->where(['sell_id' => $value['sell_id'],'b.materiel_type_id' => $value['materiel_type_id']])
                            ->where(['repeal_status' => 0,'delete_flag' => 0])->first();
                        $remaining_num = $value['num'] - $returnData['total_return_num'];//销售数量还剩多少可退数量
                        if($value['return_num'] > $remaining_num){
                            return ['code'=>1,'msg'=>'商品:'.$materielInfo['materiel_name'].'的退货数量超过了剩余数量！可退货数量为：'.$remaining_num,'data'=>''];
                        }
                        $value['num'] = $value['return_num'];
                    }

                    $money += ($value['price']*$value['num']);
                    #$goods = SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id']])->first();
//                    $goods = SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id'],
//                        'warehouse_id'=>$value['warehouse_id'],'shelf_id'=>$shelf_id,'location_id'=>$location_id])->first();
                    $goods = SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id'],
                        'warehouse_id'=>$value['warehouse_id']])->first();


                    $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

                    $value['name'] = $materielInfo['materiel_name'];
                    $value['type_name'] = $materielInfo['type_name'];
                    $value['materiel_no'] = $materielInfo['materiel_no'];
                    $value['image'] = $materielInfo['materiel_image'];
                    $value['warehouse'] = $storageInfo['storage_name'];

                    $value['warehouse_id'] = $value['warehouse_id'];
                    $value['shelf_id'] = $shelf_id;
                    $value['location_id'] = $location_id;

                    //更新
                    if($goods){
                        #SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id']])->update($value);
//                        SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id'],
//                            'warehouse_id'=>$value['warehouse_id'],'shelf_id'=>$shelf_id,'location_id'=>$location_id])->update($value);
                        SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id'],
                            'warehouse_id'=>$value['warehouse_id']])->update($value);

                    }else{//添加
                        $value['main_id'] = $data['main_id'];
                        $value['return_id'] = $data['id'];
                        $value['created_at'] = time();
                        SalesReturnGoodsDetailModel::insert($value);
                    }
                }
            }

            if(!empty($data['package_info'])) {
                $packageInfo = json_decode($data['package_info'], true);
                $packageContentInfo = [];
                SalesReturnPackageModel::where(['return_id'=>$data['id']])->delete();
                SalesReturnPackageContentModel::where(['return_id'=>$data['id']])->delete();

                foreach($packageInfo as $val) {
                    $money +=($val['price']*$val['num']);
                    $packageId = SalesReturnPackageModel::insertGetId([
                        'package_id' => $val['package_id'],
                        'price' => $val['price'],
                        'cost_price' => self::getPackageCost($val['package_id']),
                        'num' => $val['num'],
//                            'remark' => $val['remark'],
                        'main_id' => $data['main_id'],
                        'return_id' => $data['id'],
                        'created_at' => time()
                    ]);

                    foreach($val['package_content'] as $k => $v) {
                        if(empty($v['shelf_id']) || empty($v['location_id'])){
                            /* $shelf_id = ShelfService::get_default($v['storage_id'])['id'];
                            $location_id = ShelfService::get_default($shelf_id,2)['id']; */

                            $sfData = ShelfService::get_default($v['storage_id']);
                            if(!empty($sfData)){
                                $shelf_id = $sfData['id'];
                                $lData = ShelfService::get_default($shelf_id,2);
                                $location_id = $lData['id'];
                            }else{
                                $shelf_id = 0;
                                $location_id = 0;
                                $v['shelf_id']=0;
                                $v['location_id']=0;
                            }
                        }else{
                            $shelf_id = $v['shelf_id'];
                            $location_id = $v['location_id'];
                        }
                        $packageContentInfo[] = [
                            'type_id' => $v['type_id'],
                            'storage_id' => $v['storage_id'],
                            'package_content_id' => $v['id'],
                            'storage_manage_id' => $v['storage_manage_id'],
                            'return_package_id' => $packageId,
                            'num' => $v['num'],
                            'main_id' => $data['main_id'],
                            'return_id' => $data['id'],
                            'created_at' => time(),

                            'shelf_id' => $shelf_id,
                            'location_id' => $location_id,
                        ];
                    }
                }

                SalesReturnPackageContentModel::insert($packageContentInfo);
            }
            $srData = array();

            $param  = [
                'customer_name','discount','tax_rate',
                'proof_image','final_money','real_money','remark',
                'out_order_no','refund_date','is_zero_suppression'
            ];

            foreach ($data as $k=>$v){

                if(in_array($k,$param)){

                    $srData[$k]=$v;
                }
            }

            if(empty($srData['final_money'])) $srData['final_money'] = $money;

            SalesReturnModel::where(['id'=>$data['id']])->update($srData);
            $orderNo = SalesReturnModel::where('id',$data['id'])->value('order_no');
            $logData = '退货单号：'.$orderNo.'信息已更新!';
            CommonService::log('修改退货单', $mainInfo,$logData);
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('修改退货单异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    public static function in_by_serial($data)
    {
        $info = SalesReturnModel::where('id',$data['id'])->first();

        if($info['out_status'] == 2) {
            return ['code' => 1, 'msg' => '退货单已全部入库，无法重复操作', 'data' => ''];
        }

        $paramsArr = [];//出入库参数
        $paramsArr['in_storage_time'] = $data['in_storage_time'];
        $paramsArr['all_id'] = $data['id'];
        isset($data['remark'])?$paramsArr['remark'] = $data['remark']:$paramsArr['remark'] = '';
        $paramsArr['all_id_type'] = 2;//销售退货均为2

        $paramsArr['batch_title'] = $data['batch_title'];

        //数据处理
        $goods_info_arr = json_decode($data['goods_info'],true);
        $package_info_arr = json_decode($data['package_info'],true);

        $serial_array = [];

        if(!empty($goods_info_arr)){
            foreach ($goods_info_arr as $key => $value){
                $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('goods_id',$value['materiel_type_id'])->where('delete_flag',0)->first();

                if($goodsInfo['is_use_serial']==1){
                    if(empty($value['serial_no'])){
                        throw new \Exception('序列号不能为空');
                    }
                    $serial_no_array = explode(',',$value['serial_no']);


                    if(count($serial_no_array) != $value['num']){
                        throw new \Exception('序列号个数与入库数量不符');
                    }

                    foreach ($serial_no_array as $serial_key => $serial_data) {
                        //检查序列号是否使用
                        $number_info = SerialNumberModel::where(['goods_id' => $value['materiel_type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::UNUSEDSTATUS])->first();

                        if ($number_info) {
                            return ['code' => 1, 'msg' => '该商品：' . $value['materiel_type_id'] . '的序列号：' . $serial_data . '已被使用', 'data' => ''];
                        }
                        array_push($serial_array,$serial_data);
                    }
                }
            }
        }

        if(!empty($package_info_arr)){
            foreach ($package_info_arr as $key => $value){
                foreach ($value['package_content'] as $k => $v){
                    $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('goods_id',$v['type_id'])->where('delete_flag',0)->first();

                    if($goodsInfo['is_use_serial'] == 1){
                        $serial_no_array = explode(',',$v['serial_no']);
                        if(empty($serial_no_array)){
                            throw new \Exception('序列号不能为空');
                        }

                        if(count($serial_no_array) != $value['num']*$v['num']){
                            throw new \Exception('序列号个数与入库数量不符');
                        }

                        foreach ($serial_no_array as $serial_key => $serial_data) {


                            //检查序列号是否使用
                            $number_info = SerialNumberModel::where(['goods_id' => $v['type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::UNUSEDSTATUS])->first();

                            if ($number_info) {
                                return ['code' => 1, 'msg' => '该商品：' . $v['type_id'] . '的序列号：' . $serial_data . '已被使用', 'data' => ''];
                            }

                            array_push($serial_array,$serial_data);
                        }
                    }
                }
            }
        }

        $result = self::inStorage($data, $paramsArr);

        if(empty($result['code'])){
            //插入序列号关联表
            $serial = implode(',',$serial_array);
            if(!empty($serial)){
                DB::table('sales_out_serial_number')->insert([
                    ['main_id' =>  $data['main_id'], 'created_at' => time(), 'return_id' => $data['id'], 'serial_number' => $serial, 'status' => 1],
                ]);
            }
        }

        return $result;
    }


    public static function outWithBatch($data){

        $info = SalesReturnModel::where('id',$data['id'])->first();

        if($info['out_status'] == 2) {
            return ['code' => 1, 'msg' => '退货单已全部入库，无法重复操作', 'data' => ''];
        }

        $paramsArr = [];//出入库参数
        $paramsArr['in_storage_time'] = $data['in_storage_time'];
        $paramsArr['all_id'] = $data['id'];
        isset($data['remark'])?$paramsArr['remark'] = $data['remark']:$paramsArr['remark'] = '';
        $paramsArr['all_id_type'] = 2;//销售退货均为2

        $paramsArr['batch_title'] = $data['batch_title'];

        DB::beginTransaction();

        try {

            //数据处理
            $goods = json_decode($data['goods_info'],true);
            $package = json_decode($data['package_info'],true);

            if(!empty($goods) || !empty($package)) {

                if(!empty($goods)) {
                    $materielOutResult = self::returnMaterielPartStep1($data['id'], $goods, $data);

                    if($materielOutResult['code'] != 0) {
                        return $materielOutResult;
                    }
                }

                if(!empty($package)) {
                    $materielOutResult = SELF::returnPackagePart($data['id'], $package, $data);
                    if($materielOutResult['code'] != 0) {
                        return $materielOutResult;
                    }
                }
            }

            $result = self::inStorage($data, $paramsArr);

            DB::commit();
            return $result;
        }catch(\Exception $e) {
            DB::rollBack();
            Log::debug('退货单部分出库异常'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function returnMaterielPartStep1($id, $goods, $data)
    {
        $sellOutStorageNewData = [];
        $sellOutStorageAgainData = [];
        $outStorageLogInfo = [];
        $logOutPackageInfo = [];
        $sellGoodsList = [];

        $info = SalesReturnModel::where('id',$data['id'])->first();

        foreach($goods as $value) {

            $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('id',$value['materiel_type_id'])->where('delete_flag',0)->first();

            $returnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id' => $data['id']
            ])
                ->first();

            if($goodsInfo['is_use_serial'] == 1){

                if(empty($value['serial_no'])){

                    throw new \Exception('序列号不能为空');
                }
                $serial_no_array = explode(',',$value['serial_no']);
                if(count($serial_no_array) != $value['num']){
                    throw new \Exception('序列号个数与入库数量不符');
                }

                foreach ($serial_no_array as $serial_key => $serial_data) {

                    //检查序列号是否使用
                    $number_info = SerialNumberModel::where(['goods_id' => $value['materiel_type_id'], 'serial_no' => $serial_data])->where('status',0)->first();

                    if(!empty($number_info)){

                        $bool = SerialNumberModel::where(
                            [
                                'serial_no' => $serial_data,
                                'status'    => SerialNumberModel::USEDSTATUS,
                                'goods_id'   => $number_info['goods_id'],

                            ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                        SalesOutSerialNumberModel::insert([
                            'main_id' =>  $data['main_id'],
                            'created_at' => time(),
                            'return_id' => $data['id'],
                            'serial_number' => $serial_data,
                            'status' => 1,
                            'type_id'=>$value['materiel_type_id'],
                            'return_goods_detail_id'=>$returnGoodsDetailInfo['id']
                        ]);
                    }else{

                        return ['code'=>1,'msg'=>'序列号:'.$serial_data.'不存在','data'=>''];
                    }
                }
            }

            if(!empty($value['batch_info'])){
                foreach($value['batch_info'] as $k => $val) {

                    $storageBatchInfo = StorageBatchModel::select(
                        'a.id',
                        'b.id as storage_manage_id',
                        'in_storage_num',
                        'materiel_mean_cost',
                        'type_id as materiel_type_id',
                        'c.materiel_name',
                        'c.type_name',
                        'c.materiel_no',
                        'storage_id',
                        'd.storage_name',
                        'd.storage_address',
                        'alert_num',
                        'batch_left_num',
                        'b.materiel_class_id',
                        'class_name',
                        'class_no',
                        'f.id as sid'
                    )
                        ->from('storage_batch as a')
                        ->leftJoin('storage_manage as b', 'a.storage_manage_id', '=', 'b.id')
                        ->leftJoin('materiel_type as c', 'c.id', '=', 'b.type_id')
                        ->leftJoin('storage as d', 'd.id', '=', 'b.storage_id')
                        ->leftJoin('materiel_class as e', 'e.id', '=', 'c.materiel_class_id')
                        ->leftJoin('sales_return_goods_batch as f', 'f.storage_batch_id', '=', 'a.id')
                        ->leftJoin('sales_return_goods_detail as g', 'g.id', '=', 'f.return_goods_detail_id')
                        ->where('a.id', $val['batch_id'])
                        ->where('g.id', $returnGoodsDetailInfo['id'])
                        ->where('b.delete_flag', 0)
                        ->first();

                    if(empty($storageBatchInfo)) {
                        throw new \Exception('库存信息不存在，无法入库');
                    }

                    if($storageBatchInfo['materiel_type_id'] != $value['materiel_type_id']) {
                        throw new \Exception('批次号对应的商品和需出库商品信息不一致，无法完成操作');
                    }
                    StorageBatchModel::where('id', $storageBatchInfo['id'])
                        ->increment('batch_left_num', $val['num']);

                    SalesReturnGoodsBatchModel::where('id', $storageBatchInfo['sid'])
                        ->decrement('rest_num', $val['num']);
                }
            }
        }

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    static private function returnPackagePart($id, $package, $data)
    {
        $outNum = 0;
        $sellGoodsList = [];

        $info = SalesReturnModel::where('id',$data['id'])->first();

        foreach($package as $value) {
            foreach ($value['package_content'] as $val) {

                $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('id',$val['type_id'])->where('delete_flag',0)->first();

                if($goodsInfo['is_use_serial'] == 1){
                    $serial_no_array = explode(',',$val['serial_no']);
                    if(empty($serial_no_array)){
                        throw new \Exception('序列号不能为空');
                    }

                    if(count($serial_no_array) != $value['num']*$val['num']){
                        throw new \Exception('序列号个数与入库数量不符');
                    }

                    foreach ($serial_no_array as $serial_key => $serial_data) {

                        //检查序列号是否使用
                        $number_info = SerialNumberModel::where(['goods_id' => $val['type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::USEDSTATUS])->first();

                        if (!$number_info) {

                            return ['code' => 1, 'msg' => '该商品：' . $val['type_id'] . '的序列号：' . $serial_data . '不存在', 'data' => ''];
                        }
                        SerialNumberModel::where(['serial_no' => $serial_data,'status' => SerialNumberModel::USEDSTATUS,
                            'goods_id' => $number_info['goods_id'],
                        ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                        SalesReturnPackageSerialNumberModel::insert([

                            'main_id' =>  $data['main_id'],
                            'created_at' => time(),
                            'return_id' => $id,
                            'serial_number' => $serial_data,
                            'status' => 1,
                            'return_package_content_id'=>$val['id'],
                            'type_id'=>$val['type_id']
                        ]);
                    }
                }
                $num = 0;
                if(!empty($val['batch_info'])){
                    foreach($val['batch_info'] as $v) {
                        $num += $v['num'];

                        $storageBatchInfo = StorageBatchModel::select(
                            'a.id',
                            'b.id as storage_manage_id',
                            'batch_no',
                            'batch_left_num',
                            'b.storage_id',
                            'b.materiel_mean_cost',
                            'b.type_id as materiel_type_id',
                            'd.materiel_name',
                            'd.type_name',
                            'd.materiel_no',
                            'b.materiel_class_id',
                            'in_storage_num',
                            'alert_num',
                            'f.id as sid',
                            'package_content_id',
                            'f.rest_num'
                        )
                            ->from('storage_batch as a')
                            ->leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
                            ->leftJoin('materiel_type as d', 'd.id', '=', 'b.type_id')
                            ->leftJoin('sales_return_package_batch as f', 'f.storage_manage_id', '=', 'b.id')
                            ->leftJoin('sales_return_package_content as g', 'g.id', '=', 'f.return_package_content_id')
                            ->where('b.id', $v['storage_manage_id'])
                            ->where('g.id', $val['id'])
                            ->where('a.id', $v['batch_id'])
                            ->where('b.delete_flag', 0)
                            ->where('f.return_id', $id)
                            ->first();

                        if(empty($storageBatchInfo)) {

                            throw new \Exception('套餐内商品暂无指定的库存信息，请查验后重试');
                        }

                        if($storageBatchInfo['batch_left_num'] < $v['num']) {
                            throw new \Exception('批次剩余数量不足,无法出库');
                        }

                        if($storageBatchInfo['in_storage_num'] < $v['num']) {
                            throw new \Exception('库存数量不足,无法出库');
                        }

                        StorageBatchModel::where('id', $v['batch_id'])
                            ->increment('batch_left_num', $v['num']);

                        SalesReturnPackageBatchModel::where('id', $storageBatchInfo['sid'])
                            ->decrement('rest_num', $v['num']);
                    }
                }
            }
        }

        return ['code' => 0, 'msg' => 'success', 'data' => ''];
    }

    static public function in($data)
    {
        $info = SalesReturnModel::where('id',$data['id'])->first();

        if($info['out_status'] == 2) {
            return ['code' => 1, 'msg' => '退货单已全部入库，无法重复操作', 'data' => ''];
        }

        $paramsArr = [];//出入库参数
        $paramsArr['in_storage_time'] = $data['in_storage_time'];
        $paramsArr['all_id'] = $data['id'];
        isset($data['remark'])?$paramsArr['remark'] = $data['remark']:$paramsArr['remark'] = '';
        $paramsArr['all_id_type'] = 2;//销售退货均为2

        $paramsArr['batch_title'] = $data['batch_title'];

        //数据处理
        $goods_info_arr = json_decode($data['goods_info'],true);
        $package_info_arr = json_decode($data['package_info'],true);

        $serial_array = [];

        if(!empty($goods_info_arr)){
            foreach ($goods_info_arr as $key => $value){
                $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('id',$value['materiel_type_id'])->where('delete_flag',0)->first();

                $returnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                    'materiel_type_id' => $value['materiel_type_id'],
                    'warehouse_id' => $value['warehouse_id'],
                    'return_id' => $data['id']
                ])
                    ->first();
                if($goodsInfo['is_use_serial']==1){
                    if(empty($value['serial_no'])){
                        throw new \Exception('序列号不能为空');
                    }
                    $serial_no_array = explode(',',$value['serial_no']);


                    if(count($serial_no_array) != $value['num']){
                        throw new \Exception('序列号个数与入库数量不符');
                    }

                    foreach ($serial_no_array as $serial_key => $serial_data) {
                        //检查序列号是否使用
                        $number_info = SerialNumberModel::where(['goods_id' => $value['materiel_type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::USEDSTATUS])->first();

                        if (!$number_info) {
                            return ['code' => 1, 'msg' => '该商品：' . $value['materiel_type_id'] . '的序列号：' . $serial_data . '不存在', 'data' => ''];
                        }

                        SerialNumberModel::where(['serial_no' => $serial_data,'status' => SerialNumberModel::UNUSEDSTATUS,
                            'goods_id' => $number_info['goods_id'],
                        ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                        SalesOutSerialNumberModel::insert(
                            [
                                'main_id' =>  $data['main_id'],
                                'created_at' => time(),
                                'return_id' => $data['id'],
                                'serial_number' => $serial_data,
                                'status' => 1,
                                'type_id'=>$value['materiel_type_id'],
                                'return_goods_detail_id'=>$returnGoodsDetailInfo['id']
                            ]);
                    }
                }
            }
        }

        if(!empty($package_info_arr)){
            foreach ($package_info_arr as $key => $value){
                foreach ($value['package_content'] as $k => $v){
                    $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('id',$v['type_id'])->where('delete_flag',0)->first();

                    if($goodsInfo['is_use_serial'] == 1){
                        $serial_no_array = explode(',',$v['serial_no']);
                        if(empty($serial_no_array)){
                            throw new \Exception('序列号不能为空');
                        }

                        if(count($serial_no_array) != $value['num']*$v['num']){
                            throw new \Exception('序列号个数与入库数量不符');
                        }

                        foreach ($serial_no_array as $serial_key => $serial_data) {

                            //检查序列号是否使用
                            $number_info = SerialNumberModel::where(['goods_id' => $v['type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::USEDSTATUS])->first();

                            if (!$number_info) {
                                return ['code' => 1, 'msg' => '该商品：' . $v['type_id'] . '的序列号：' . $serial_data . '不存在', 'data' => ''];
                            }
                            SerialNumberModel::where(['serial_no' => $serial_data,'status' => SerialNumberModel::UNUSEDSTATUS,
                                'goods_id' => $number_info['goods_id'],
                            ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                            SalesReturnPackageSerialNumberModel::insert([
                                'main_id' =>  $data['main_id'],
                                'created_at' => time(),
                                'return_id' => $data['id'],
                                'serial_number' => $serial_data,
                                'status' => 1,
                                'return_package_content_id'=>$v['id'],
                                'type_id'=>$v['type_id']
                            ]);
                        }
                    }
                }
            }
        }

        $result = self::inStorage($data, $paramsArr);

        return $result;
    }

    /**
     * 退货入库前数据处理
     * @param  $data
     */
    static function frontReturnIn($data){

        $info = SalesReturnModel::where('id',$data['id'])->first();
        if($info['out_status'] == 2) {
            return ['code' => 1, 'msg' => '退货单已全部入库，无法重复操作', 'data' => ''];
        }

        $paramsArr = [];//出入库参数
        $product_info_arr = [];
        $paramsArr['all_id']          = $data['id'];
        $paramsArr['all_id_type']     = 2;//销售退货均为2
        $paramsArr['batch_title']     = $data['batch_title'];
        $paramsArr['in_storage_time'] = $data['in_storage_time'];
        $paramsArr['remark']          = !empty($data['remark'])  ? $data['remark']:'';
        //数据处理
        $goods_info_arr   = json_decode($data['goods_info'],true);
        if(!empty($data['product_info'])){
            $product_info_arr = json_decode($data['product_info'],true);
        }
        $package_info_arr = json_decode($data['package_info'],true);
        $serial_array = [];

        if(!empty($goods_info_arr)){//普通商品

            foreach ($goods_info_arr as $key => $value){

                $goodsInfo = MaterielsTypeModel::select('a.materiel_name','b.id','is_product_materiel','is_use_serial','warehouse_id')
                    ->from('materiel_type as a')
                    ->leftJoin('sales_return_goods_detail as b','b.materiel_type_id','=','a.id')
                    ->where([
                        'return_id'        => $data['id'],
                        'warehouse_id'     => $value['warehouse_id'],
                        'materiel_type_id' => $value['materiel_type_id']
                    ])->where('delete_flag',0)->first();

                if(empty($goodsInfo)) return ['code'=>1,'msg'=>'退货商品'.$goodsInfo['materiel_name'].',不存在','data'=>''];

                $storageInfo = StorageModel::select('b.*')->from('storage as a')
                    ->leftJoin('storage_manage as b','b.storage_id','=','a.id')
                    ->where('a.id',$goodsInfo['warehouse_id'])
                    ->where('a.delete_flag',1)
                    ->where('b.delete_flag',1)->first();

                if(!empty($storageInfo)){
                    return ['code'=>1,'msg'=>'退货商品'.$goodsInfo['materiel_name'].'的'.$storageInfo['storage_name'].'仓库已被删除，请使用快速入库进行操作','data'=>''];
                }

                if($goodsInfo['is_use_serial'] == 1){
                    //普通商品开启序列号处理
                    if(empty($value['serial_no'])){

                        return ['code'=>1,'msg'=>'序列号不能为空','data'=>''];
                    }

                    $serial_no_array = explode(',',$value['serial_no']);

                    if(count($serial_no_array) != $value['num']){

                        return ['code'=>1,'msg'=>'商品'.$goodsInfo['materiel_name'].'选择的序列号与退货数量不符！','data'=>''];
                    }

                    foreach ($serial_no_array as $serial_key => $serial_data) {
                        //检查序列号是否使用
                        $number_info = SerialNumberModel::where(['goods_id' => $value['materiel_type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::USEDSTATUS])->first();

                        if (!$number_info) {
                            return ['code' => 1, 'msg' => '该商品' . $goodsInfo['materiel_name'] . '的序列号：' . $serial_data . '不存在', 'data' => ''];
                        }

//                           SerialNumberModel::where(['serial_no' => $serial_data,'status' => SerialNumberModel::USEDSTATUS,
//                               'goods_id' => $number_info['goods_id'],
//                           ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                        SalesOutSerialNumberModel::insert(
                            [
                                'main_id' =>  $data['main_id'],
                                'created_at' => time(),
                                'return_id' => $data['id'],
                                'serial_number' => $serial_data,
                                'status' => 1,
                                'type_id'=>$value['materiel_type_id'],
                                'return_goods_detail_id'=>$goodsInfo['id']
                            ]);
                    }
                }
            }
        }

        if(!empty($product_info_arr)){//有组件的套餐
            $info['type'] = 2;
            switch ($info['type']){
                case 1://套件返仓

                    ;break;
                case 2://整体入库
                    foreach ($product_info_arr as $key => $value){
                        //查询组件信息
                        $productInfo = MaterielsTypeModel::select('warehouse_id','a.materiel_name','a.id','b.id as return_goods_detail_id','is_product_materiel','is_use_serial','b.num','b.in_num')
                            ->from('materiel_type as a')
                            ->leftJoin('sales_return_goods_detail as b','b.materiel_type_id','=','a.id')
                            ->with('productContent',function($query){
                                $query->select('materiel_product_content.*','b.materiel_name')
                                    ->leftJoin('materiel_type as b','b.id','=','materiel_product_content.type_id');
                            })
                            ->where([
                                'is_product_materiel' => 1,
                                'return_id'           => $data['id'],
                                'warehouse_id'        => $value['warehouse_id'],
                                'materiel_type_id'    => $value['materiel_type_id']
                            ])->where('delete_flag',0)->first();

                        //判断是否有套餐商品信息
                        if(empty($productInfo)) return ['code'=>1,'msg'=>'套餐'.$productInfo['materiel_name'].',不存在','data'=>''];

                        $storageInfo = StorageModel::select('b.*')->from('storage as a')
                            ->leftJoin('storage_manage as b','b.storage_id','=','a.id')
                            ->where('a.id',$productInfo['warehouse_id'])
                            ->where('a.delete_flag',1)
                            ->where('b.delete_flag',1)->first();
                        if(!empty($storageInfo)){
                            return ['code'=>1,'msg'=>'套餐'.$productInfo['materiel_name'].'的'.$storageInfo['storage_name'].'仓库已被删除，请使用快速入库进行操作','data'=>''];
                        }

                        //获取套餐库存信息
                        $productStorageInfo = StorageManageModel::where([
                            'type_id' => $value['materiel_type_id'],
                            'storage_id' => $value['warehouse_id']
                        ])
                            ->first();

                        $daiTotalNum = 0;
                        $zaiTotalNum = 0;
                        $zongTotalNum = 0;
                        //计算套餐里面组件总数量、已入库数量 、可操作数量
                        $daiTotalNum  = $value['num'];//待入库总数量
                        $zaiTotalNum  = $productInfo['in_num'];//已入库总数量
                        $zongTotalNum = $productInfo['num'];//应入库的总数量
                        if($zongTotalNum - $zaiTotalNum < $daiTotalNum){
                            $nn = $zongTotalNum - $zaiTotalNum;
                            return ['code'=>1,'msg'=>'本次操作数量大于了可入库数量，套餐商品可入库数量为：'.$nn,'data'=>''];
                        }
                        //套餐开启序列号处理
                        if(!empty($value['product_content'])){
                            foreach ($value['product_content'] as $pk=>$pv){

                                //$oneSerialTotalNum = $pv['num'] * $value['num'];//组件数量=套餐数量*组件设置数量

                                $pInfo = MaterielTypeModel::where('id',$pv['type_id'])->where('delete_flag',0)->first();

                                if($pInfo['is_use_serial'] == 1){
                                    if(empty($pv['serial_info'])){
                                        return ['code'=>1,'msg'=>'套餐商品'.$pInfo['materiel_name'].'已开启序列号，请选择序列号！','data'=>''];
                                    }
                                    $serialNumber = 0;
                                    $serialNumberList = "";
                                    foreach ($pv['serial_info'] as $sVal){
                                        $serialNumber += $sVal['num'];
//                                        $serialInfo = SerialNumberModel::where(['id' => $sVal['serial_id'],'status' => 0])->first();
                                        $serialInfo = SerialNumberModel::where(['id' => $sVal['serial_id']])->first()->toArray();
                                        if(!empty($serialInfo)){
                                            if ($serialInfo['status'] != 0) {
                                                return ['code' => 1, 'msg' => '套餐商品'.$pInfo['materiel_name'].'的序列号' . $serialInfo['serial_no'] . '不存在', 'data' => ''];
                                            }
                                        }else{
                                            return ['code'=>1,'msg'=>'套餐商品'.$pInfo['materiel_name'].'已开启序列号，请选择序列号！','data'=>''];
                                        }

                                        $serialNumberList .=$serialInfo['serial_no'].',';
                                        if(!empty($serialInfo['storage_manage_id'])){
                                            $storageInfo = StorageModel::select('b.*')->from('storage as a')
                                                ->leftJoin('storage_manage as b','b.storage_id','=','a.id')
                                                ->where('b.id',$serialInfo['storage_manage_id'])
                                                ->where('a.delete_flag',1)
                                                ->where('b.delete_flag',1)->first();

                                            if(!empty($storageInfo)){
                                                return ['code'=>1,'msg'=>'套餐商品'.$pInfo['materiel_name'].'的'.$storageInfo['storage_name'].'仓库已被删除，请使用快速入库进行操作','data'=>''];
                                            }
                                        }
                                        $updSerialNumberData[]=[
                                            'id' => $serialInfo['id'],
                                            'package_storage_id' => $productStorageInfo['id'],
                                            'sell_id' => 0,
                                            'status' => 1
                                        ];
                                        $SalesOutSerialNumberData[]=[
                                            'main_id' =>  $data['main_id'],
                                            'created_at' => time(),
                                            'return_id' => $data['id'],
                                            'serial_number' => $serialInfo['serial_no'],
                                            'status' => 1,
                                            'type_id' => $pv['type_id'],
                                            'return_goods_detail_id' => $productInfo['return_goods_detail_id'],
                                            'goods_flag'=>2
                                        ];
                                    }

                                    DB::beginTransaction();
                                    try {
                                        if(!empty($SalesOutSerialNumberData))
                                            SalesOutSerialNumberModel::insert($SalesOutSerialNumberData);
                                        if(!empty($updSerialNumberData)){
                                            batch()->update(new SerialNumberModel(), $updSerialNumberData, 'id');
                                        }
                                        if(!empty($serialNumberList))
                                            $serialNumberList = substr($serialNumberList,0,strrpos($serialNumberList,","));
                                        //echo $oneSerialTotalNum .'===='.$serialNumber;die;
                                        if($pv['num'] != $serialNumber){

                                            return ['code'=>1,'msg'=>'选择序列号个数与商品'.$pInfo['materiel_name'].'可入库数量不符','data'=>''];
                                        }

                                        DB::commit();
                                    } catch (\Exception $e) {
                                        DB::rollBack();
                                        return ['code'=>1,'msg'=>'退货异常','data'=>''];
                                    }

                                }
                            }
                        }

                    }
            }
        }

        if(!empty($package_info_arr)){//老套餐商品
            foreach ($package_info_arr as $key => $value){

                foreach ($value['package_content'] as $k => $v){
                    $goodsInfo = MaterielsTypeModel::select('is_use_serial')->where('id',$v['type_id'])->where('delete_flag',0)->first();

                    if($goodsInfo['is_use_serial'] == 1){
                        $serial_no_array = explode(',',$v['serial_no']);
                        if(empty($serial_no_array)){
                            throw new \Exception('序列号不能为空');
                        }

                        if(count($serial_no_array) != $value['num']*$v['num']){
                            throw new \Exception('序列号个数与入库数量不符');
                        }

                        foreach ($serial_no_array as $serial_key => $serial_data) {

                            //检查序列号是否使用
                            $number_info = SerialNumberModel::where(['goods_id' => $v['type_id'], 'serial_no' => $serial_data, 'status' => SerialNumberModel::USEDSTATUS])->first();

                            if (!$number_info) {
                                return ['code' => 1, 'msg' => '该商品：' . $v['type_id'] . '的序列号：' . $serial_data . '不存在', 'data' => ''];
                            }
//                           $bool=SerialNumberModel::where(['serial_no' => $serial_data,'status' => SerialNumberModel::UNUSEDSTATUS,
//                               'goods_id' => $number_info['goods_id'],
//                           ])->update(['status' => SerialNumberModel::UNUSEDSTATUS]);

                            SalesReturnPackageSerialNumberModel::insert([
                                'main_id' =>  $data['main_id'],
                                'created_at' => time(),
                                'return_id' => $data['id'],
                                'serial_number' => $serial_data,
                                'status' => 1,
                                'return_package_content_id'=>$v['id'],
                                'type_id'=>$v['type_id']
                            ]);
                        }
                    }
                }
            }
        }

        $result = self::returnInStorage($data, $paramsArr);

        return $result;
    }

    /**
     * 退货入库
     * @param unknown $data
     * @param unknown $paramsArr
     */
    static private function returnInStorage($data, $paramsArr)
    {
        DB::beginTransaction();
        try {
            $pInfo=[];
            if(!empty($data['product_info'])){
                $productInfo = json_decode($data['product_info'],true);
            }
            if($data['status'] == 0) {
                $goodsInfo = json_decode($data['goods_info'], true);
                $packageInfo = json_decode($data['package_info'], true);
            }
            else {
                $goods = json_decode($data['goods_info'], true);
                $package = json_decode($data['package_info'], true);
                $goodsInfo = [];
                $packageInfo = [];


                foreach($goods as $key => $value) {

                    if(empty($value['shelf_id']) || empty($value['location_id'])){
                        /*  $shelf_id = ShelfService::get_default($value['warehouse_id'])['id'];
                         $location_id = ShelfService::get_default($shelf_id,2)['id']; */

                        $sfData = ShelfService::get_default($value['warehouse_id']);
                        if(!empty($sfData)){
                            $shelf_id = $sfData['id'];
                            $lData = ShelfService::get_default($shelf_id,2);
                            $location_id = $lData['id'];
                        }else{
                            $shelf_id = 0;
                            $location_id = 0;
                            $value['shelf_id'] = 0;
                            $value['location_id'] = 0;
                        }
                    }else{
                        $shelf_id = $value['shelf_id'];
                        $location_id = $value['location_id'];
                    }

                    $returnDetail = SalesReturnGoodsDetailModel::selectRaw('
                    price,
                    materiel_type_id,
                    warehouse_id,
                    (num - in_num) as num,
                    shelf_id,
                    location_id
                ')
                        ->where([
                            'return_id' => $data['id'],
                            'materiel_type_id' => $value['materiel_type_id']
                        ])->whereRaw('num > in_num')->first();

                    $goodsInfo[] = [
                        'price' => $returnDetail['price'],
                        'materiel_type_id' => $returnDetail['materiel_type_id'],
                        'warehouse_id' => $returnDetail['warehouse_id'],
                        'num' => $returnDetail['num'],
                        'remark' => $value['remark'],
                        'shelf_id' => $shelf_id,
                        'location_id' => $location_id,
                        'serial_no' => empty($value['serial_no']) ? '' : $value['serial_no'],

                    ];
                }

                foreach($package as $k => $v) {
                    $packageInfos = SalesReturnPackageModel::selectRaw('
                    id,
                    price,
                    package_id,
                    (num - in_num) as num
                ')
                        ->with('PackageContent')
                        ->where('package_id', $v['package_id'])
                        ->where('return_id', $data['id'])
                        ->whereRaw('num > in_num')->first();

                    $packageInfo[] = [
                        'id' => $packageInfos['id'],
                        'price' => $packageInfos['price'],
                        'package_id' => $packageInfos['package_id'],
                        'num' => $packageInfos['num'],
                        'remark' => $v['remark'],
                        'package_content' => $v['package_content']
                    ];
                }
            }
            if(!empty($productInfo)){
                foreach($productInfo as $pk => $pv) {//组件套餐商品

                    if(empty($pv['shelf_id']) || empty($pv['location_id'])){

                        $sfData = ShelfService::get_default($pv['warehouse_id']);
                        if(!empty($sfData)){
                            $shelf_id = $sfData['id'];
                            $lData = ShelfService::get_default($shelf_id,2);
                            $location_id = $lData['id'];
                        }else{
                            $shelf_id = 0;
                            $location_id = 0;
                            $pv['shelf_id'] = 0;
                            $pv['location_id'] = 0;
                        }
                    }else{
                        $shelf_id = $pv['shelf_id'];
                        $location_id = $pv['location_id'];
                    }

                    $returnDetail = SalesReturnGoodsDetailModel::selectRaw('
                                price,
                                materiel_type_id,
                                warehouse_id,
                                (num - in_num) as num,
                                shelf_id,
                                location_id
                            ')->where([
                        'return_id' => $data['id'],
                        'materiel_type_id' => $pv['materiel_type_id']
                    ])->whereRaw('num > in_num')->first();
                    $serialNumberList="";
                    if(!empty($pv['serial_info'])){
                        foreach ($pv['serial_info'] as $sVal){
                            $serialInfo = SerialNumberModel::where(['id'=>$sVal['serial_id'],'status'=>0])->first();
                            if(!empty($serialInfo))
                                $serialNumberList .= $serialNumberList.',';
                        }
                    }
                    if(!empty($serialNumberList))
                        $serialNumberList = substr($serialNumberList,0,strrpos($serialNumberList,","));
                    $pInfo[] = [
                        'price' => $returnDetail['price'],
                        'materiel_type_id' => $returnDetail['materiel_type_id'],
                        'warehouse_id' => $returnDetail['warehouse_id'],
                        'num' => $returnDetail['num'],
                        'remark' => $pv['remark'],
                        'shelf_id' => $shelf_id,
                        'location_id' => $location_id,
                        'serial_no' => $serialNumberList
                    ];
                }
            }

            if(!empty($pInfo)) {
                $paramsArr['content'] = self::productInStorage($paramsArr, $pInfo, $data);

                //调用入库
                $res = StorageManageService::zongInStorage($data['user_id'], $data['main_id'], $paramsArr,$flag = 1);

                if($res['code']){
                    return $res;
                }
            }

            if(!empty($goodsInfo)) {
                $paramsArr['content'] = self::materielInStorage($paramsArr, $goodsInfo, $data);

                //调用入库
                $res = StorageManageService::oldInStorage($data['user_id'], $data['main_id'], $paramsArr,$flag = 1);

                if($res['code']){
                    return $res;
                }
            }

            if(!empty($packageInfo)) {
                foreach($packageInfo as $k1 => $v1) {
                    //退货单套餐入库记录
                    $salesReturnInPackageInfo = SalesReturnInPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    //退货单套餐信息
                    $salesReturnPackageInfo = SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    $packageInfo1 = PackageModel::where('id', $v1['package_id'])->first();

                    if(!empty($salesReturnInPackageInfo)) {

                        //剩余未入库数量
                        $restPackageNum = $salesReturnPackageInfo['num'] - $salesReturnInPackageInfo['num'];
                        if($restPackageNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restPackageNum,
                                'data' => ''
                            ];
                        }

                        SalesReturnInPackageModel::where('id', $salesReturnInPackageInfo['id'])
                            ->increment('num', $v1['num'],[
                                'remark' => $v1['remark']
                            ]);

                        self::generatePackageLog($salesReturnInPackageInfo, $data, $v1, $packageInfo1,$flag=1);
                    }
                    else {
                        $restNum = $salesReturnPackageInfo['num'] - $salesReturnPackageInfo['in_num'];
                        if($restNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restNum,
                                'data' => ''
                            ];
                        }

                        self::generatePackageLog([], $data, $v1, $packageInfo1,$flag=1);
                    }

                    SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->increment('in_num', $v1['num']);
                }
            }

            $salesGoodsInfo = SalesReturnGoodsDetailModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            $salesPackageInfo = SalesReturnPackageModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            if(empty($salesGoodsInfo) && empty($salesPackageInfo)) {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 2]);
            }
            else {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 1]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch (\Exception $e) {
            DB::rollBack();
            Log::debug('退货单入库异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function inStorage($data, $paramsArr)
    {
        DB::beginTransaction();
        try {

            if($data['status'] == 0) {
                $goodsInfo = json_decode($data['goods_info'], true);
                $packageInfo = json_decode($data['package_info'], true);

            }
            else {
                $goods = json_decode($data['goods_info'], true);
                $package = json_decode($data['package_info'], true);

                $goodsInfo = [];
                $packageInfo = [];
                foreach($goods as $key => $value) {

                    if(empty($value['shelf_id']) || empty($value['location_id'])){
                        /*  $shelf_id = ShelfService::get_default($value['warehouse_id'])['id'];
                         $location_id = ShelfService::get_default($shelf_id,2)['id']; */

                        $sfData = ShelfService::get_default($value['warehouse_id']);
                        if(!empty($sfData)){
                            $shelf_id = $sfData['id'];
                            $lData = ShelfService::get_default($shelf_id,2);
                            $location_id = $lData['id'];
                        }else{
                            $shelf_id = 0;
                            $location_id = 0;
                            $value['shelf_id'] = 0;
                            $value['location_id'] = 0;
                        }
                    }else{
                        $shelf_id = $value['shelf_id'];
                        $location_id = $value['location_id'];
                    }

                    $returnDetail = SalesReturnGoodsDetailModel::selectRaw('
                    price,
                    materiel_type_id,
                    warehouse_id,
                    (num - in_num) as num,
                    shelf_id,
                    location_id
                ')
                        ->where([
                            'return_id' => $data['id'],
                            'materiel_type_id' => $value['materiel_type_id']
                        ])->whereRaw('num > in_num')->first();

                    $goodsInfo[] = [
                        'price' => $returnDetail['price'],
                        'materiel_type_id' => $returnDetail['materiel_type_id'],
                        'warehouse_id' => $returnDetail['warehouse_id'],
                        'num' => $returnDetail['num'],
                        'remark' => $value['remark'],
                        'shelf_id' => $shelf_id,
                        'location_id' => $location_id,
                        'serial_no' => empty($value['serial_no']) ? '' : $value['serial_no'],

                    ];
                }
                foreach($package as $k => $v) {
                    $packageInfos = SalesReturnPackageModel::selectRaw('
                    id,
                    price,
                    package_id,
                    (num - in_num) as num
                ')
                        ->with('PackageContent')
                        ->where('package_id', $v['package_id'])
                        ->where('return_id', $data['id'])
                        ->whereRaw('num > in_num')->first();

                    $packageInfo[] = [
                        'id' => $packageInfos['id'],
                        'price' => $packageInfos['price'],
                        'package_id' => $packageInfos['package_id'],
                        'num' => $packageInfos['num'],
                        'remark' => $v['remark'],
                        'package_content' => $v['package_content']
                    ];
                }
            }

            if(!empty($goodsInfo)) {
                $paramsArr['content'] = self::materielInStorage($paramsArr, $goodsInfo, $data);

                //调用入库
                $res = StorageManageService::oldInStorage($data['user_id'], $data['main_id'], $paramsArr,$flag = 1);

                if($res['code']){
                    return $res;
                }
            }

            if(!empty($packageInfo)) {
                foreach($packageInfo as $k1 => $v1) {
                    //退货单套餐入库记录
                    $salesReturnInPackageInfo = SalesReturnInPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    //退货单套餐信息
                    $salesReturnPackageInfo = SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    $packageInfo1 = PackageModel::where('id', $v1['package_id'])->first();

                    if(!empty($salesReturnInPackageInfo)) {

                        //剩余未入库数量
                        $restPackageNum = $salesReturnPackageInfo['num'] - $salesReturnInPackageInfo['num'];
                        if($restPackageNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restPackageNum,
                                'data' => ''
                            ];
                        }

                        SalesReturnInPackageModel::where('id', $salesReturnInPackageInfo['id'])
                            ->increment('num', $v1['num'],[
                                'remark' => $v1['remark']
                            ]);

                        self::generatePackageLog($salesReturnInPackageInfo, $data, $v1, $packageInfo1,$flag=1);
                    }
                    else {
                        $restNum = $salesReturnPackageInfo['num'] - $salesReturnPackageInfo['in_num'];
                        if($restNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restNum,
                                'data' => ''
                            ];
                        }

                        self::generatePackageLog([], $data, $v1, $packageInfo1,$flag=1);
                    }

                    SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->increment('in_num', $v1['num']);
                }
            }

            $salesGoodsInfo = SalesReturnGoodsDetailModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            $salesPackageInfo = SalesReturnPackageModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            if(empty($salesGoodsInfo) && empty($salesPackageInfo)) {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 2]);
            }
            else {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 1]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch (\Exception $e) {
            DB::rollBack();
            Log::debug('退货单入库异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function generatePackageLog($salesReturnInPackageInfo, $data, $v1, $packageInfo,$flag = 0)
    {
        DB::enableQueryLog();

        try {
            if (empty($salesReturnInPackageInfo)) {
                $newId = SalesReturnInPackageModel::insert([
                    'package_id' => $v1['package_id'],
                    'num' => $v1['num'],
                    'price' => $v1['price'],
                    'return_id' => $data['id'],
                    'remark' => empty($v1['remark']) ? '' : $v1['remark']
                ]);
            }

            $newLogPackageId = LogPackageModel::insertGetId([
                'package_id' => $v1['package_id'],
                'package_name' => $packageInfo['package_name'],
                'num' => $v1['num'],
                'all_id_type' => 3,
                'all_id' => $data['id'],
                'user_id' => $data['user_id'],
                'main_id' => $data['main_id'],
                'created_at' => time()
            ]);

            foreach ($v1['package_content'] as $k => $v) {
                if(empty($v['shelf_id']) || empty($v['location_id'])){
                    /* $shelf_id = ShelfService::get_default($v['storage_id'])['id'];
                    $location_id = ShelfService::get_default($shelf_id,2)['id']; */

                    $sfData = ShelfService::get_default($v['storage_id']);
                    if(!empty($sfData)){
                        $shelf_id = $sfData['id'];
                        $lData = ShelfService::get_default($shelf_id,2);
                        $location_id = $lData['id'];
                    }else{
                        $shelf_id = 0;
                        $location_id = 0;
                        $v['shelf_id'] = 0;
                        $v['location_id'] = 0;
                    }
                }else{
                    $shelf_id = $v['shelf_id'];
                    $location_id = $v['location_id'];
                }

                $storageManageInfo = StorageManageModel::select(
                    'a.id as materiel_type_id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_no',
                    'b.id as materiel_class_id',
                    'b.class_name',
                    'b.class_no',
                    'c.id as storage_manage_id',
                    'c.in_storage_num',
                    'd.id as storage_id',
                    'd.storage_name',
                    'd.storage_address',
                    'c.shelf_id',
                    'c.location_id',
                    'c.materiel_mean_cost'
                )
                    ->from('storage_manage as c')
                    ->leftJoin('materiel_type as a', 'a.id', '=', 'c.type_id')
                    ->leftJoin('materiel_class as b', 'b.id', '=', 'c.materiel_class_id')
                    ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id')
                    ->where('c.id', $v['storage_manage_id'])
                    ->first();

                $logPackageContentInfo[] = [
                    'log_package_id' => $newLogPackageId,
                    'package_id' => $v1['package_id'],
                    'storage_id' => $storageManageInfo['storage_id'],
                    'storage_name' => $storageManageInfo['storage_name'],
                    'storage_address' => $storageManageInfo['storage_address'],
                    'materiel_class_id' => $storageManageInfo['materiel_class_id'],
                    'materiel_class_name' => $storageManageInfo['class_name'],
                    'materiel_class_no' => $storageManageInfo['class_no'],
                    'materiel_type_id' => $storageManageInfo['materiel_type_id'],
                    'materiel_name' => $storageManageInfo['materiel_name'],
                    'type_name' => $storageManageInfo['type_name'],
                    'materiel_no' => $storageManageInfo['materiel_no'],
                    'operate_num' => $v1['num'] * $v['num'],
                    'out_storage_manage_id' => $v['storage_manage_id'],
                    'last_storage_num' => $storageManageInfo['in_storage_num'],
                    'next_storage_num' => $storageManageInfo['in_storage_num'] + ($v1['num'] * $v['num']),
                    'all_id_type' => 5,
                    'all_id' => $data['id'],
                    'user_id' => $data['user_id'],
                    'main_id' => $data['main_id'],
                    'created_at' => time(),
                    'shelf_id' => $shelf_id,
                    'location_id' => $location_id,
                ];

                if (empty($salesReturnInPackageInfo)) {
                    SalesReturnInPackageContentModel::insert([
                        'type_id' => $storageManageInfo['materiel_type_id'],
                        'storage_id' => $v['storage_id'],
                        'package_content_id' => $v['id'],
                        'storage_manage_id' => $v['storage_manage_id'],
                        'upper_id' => $newId,
                        'num' => $v['num'],
                        'total_num' => $v1['num'] * $v['num'],
                        'user_id' => $data['user_id'],
                        'main_id' => $data['main_id'],
                        'return_id' => $data['id'],
                        'created_at' => time(),
                        'shelf_id' => $shelf_id,
                        'location_id' => $location_id,
                    ]);
                }

                StorageManageModel::where('id', $v['storage_manage_id'])
                    ->update([
                        'in_storage_num' => DB::raw('in_storage_num + ' . $v1['num'] * $v['num']),
                        'virtual_storage_num' => DB::raw('virtual_storage_num + ' . $v1['num'] * $v['num']),
                    ]);

                $batchTitle = empty($data['batch_title']) ? '' : $data['batch_title'];

                do {
                    $batchNo = $batchTitle.date('YmdHis', time()).mt_rand(1000, 9999).'0';
                }
                while(!empty($checkBatchNo));

                $batchId = MaterielService::createBatchInfoGetId(
                    $batchNo,
                    $v['storage_manage_id'],
                    $storageManageInfo['materiel_mean_cost'],
                    $v1['num'] * $v['num'],
                    0,
                    $data['main_id']
                );
                if(!$flag){
                    //处理序列号
                    $serial_no_res = SerialNumberModel::inSerialNumber($data['main_id'],$v['serial_no'],$v1['num'] * $v['num'], $storageManageInfo['materiel_type_id'],$v['storage_manage_id'],$batchNo);
                    if(!empty($serial_no_res['code'])){
                        return ['code' => 1, 'msg' => $serial_no_res['msg'], 'data' => ''];
                    }
                }
            }

            LogPackageContentModel::insert($logPackageContentInfo);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('退货入库记录及数据同步异常' . var_export($e->getMessage()));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function productInStorage($paramsArr, $productInfo, $data)
    {
        $info = [];
        foreach($productInfo as $value) {
            if(empty($value['shelf_id']) || empty($value['location_id'])){
                $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                    'materiel_type_id'=>$value['materiel_type_id'],
                    'return_id'=>$data['id'],
                    'warehouse_id' => $value['warehouse_id']
                ])
                    ->first();

                if(empty($salesReturnGoodsDetailInfo['shelf_id'])){

                    $shelf_id = ShelfService::get_default($value['warehouse_id'])['id'];
                }else{
                    $shelf_id = $salesReturnGoodsDetailInfo['shelf_id'];

                }
                if(empty($salesReturnGoodsDetailInfo['location_id'])){

                    $location_id = ShelfService::get_default($shelf_id,2)['id'];
                }else{
                    $location_id = $salesReturnGoodsDetailInfo['location_id'];

                }
            }else{
                $shelf_id = $value['shelf_id'];
                $location_id = $value['location_id'];
            }

            $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                'materiel_type_id'=>$value['materiel_type_id'],
                'return_id'=>$data['id'],
                'warehouse_id' => $value['warehouse_id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])
                ->first();

            $salesReturnInStorageInfo = SalesReturnInStorageModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id'=>$data['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])
                ->first();

            $materielInfo = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();
            $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

            if(empty($salesReturnInStorageInfo)) {

                if($value['num'] > $salesReturnGoodsDetailInfo['num']) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::insert([
                    'materiel_type_id' => $value['materiel_type_id'],
                    'name' => $materielInfo['materiel_name'],
                    'type_name' => $materielInfo['type_name'],
                    'warehouse' => $storageInfo['storage_name'],
                    'warehouse_id' => $storageInfo['id'],
                    'num' => $value['num'],
                    'return_id' => $data['id'],
                    'remark' => empty($value['remark'])?'':$value['remark'],
                    'shelf_id' => $shelf_id,
                    'location_id' => $location_id,
                ]);
            }
            else {
                if($value['num'] > ($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num'])) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::where(
                    [
                        'shelf_id'         => $shelf_id,
                        'location_id'      => $location_id,
                        'return_id'        => $data['id'],
                        'materiel_type_id' => $value['materiel_type_id'],
                        'warehouse_id'     => $value['warehouse_id']
                    ])->increment(
                    'num', $value['num'],
                    ['remark' => empty($value['remark'])?'':$value['remark']]
                );
            }

            SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id' => $data['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])->increment('in_num', $value['num']);

            $info[] = [
                'goods_id' => $materielInfo['id'],
                'name' => $materielInfo['materiel_name'],
                'type_name' => $materielInfo['type_name'],
                'num' => $value['num'],
                'warehouse' => $storageInfo['storage_name'],
                'warehouse_id' => $storageInfo['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
                'serial_no' => empty($value['serial_no']) ? '' : $value['serial_no'],
            ];
        }

        return $info;
    }

    static private function materielInStorage($paramsArr, $goodsInfo, $data)
    {
        $info = [];
        foreach($goodsInfo as $value) {
            if(empty($value['shelf_id']) || empty($value['location_id'])){
                $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                    'materiel_type_id'=>$value['materiel_type_id'],
                    'return_id'=>$data['id'],
                    'warehouse_id' => $value['warehouse_id'],
                    /* 'shelf_id' => $shelf_id,
                     'location_id' => $location_id, */
                ])
                    ->first();

                if(empty($salesReturnGoodsDetailInfo['shelf_id'])){

                    $shelf_id = ShelfService::get_default($value['warehouse_id'])['id'];
                }else{
                    $shelf_id = $salesReturnGoodsDetailInfo['shelf_id'];

                }
                if(empty($salesReturnGoodsDetailInfo['location_id'])){

                    $location_id = ShelfService::get_default($shelf_id,2)['id'];
                }else{
                    $location_id = $salesReturnGoodsDetailInfo['location_id'];

                }
            }else{
                $shelf_id = $value['shelf_id'];
                $location_id = $value['location_id'];
            }

            $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                'materiel_type_id'=>$value['materiel_type_id'],
                'return_id'=>$data['id'],
                'warehouse_id' => $value['warehouse_id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])
                ->first();

            $salesReturnInStorageInfo = SalesReturnInStorageModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id'=>$data['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])
                ->first();



            $materielInfo = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();
            $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

            if(empty($salesReturnInStorageInfo)) {

                if($value['num'] > $salesReturnGoodsDetailInfo['num']) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::insert([
                    'materiel_type_id' => $value['materiel_type_id'],
                    'name' => $materielInfo['materiel_name'],
                    'type_name' => $materielInfo['type_name'],
                    'warehouse' => $storageInfo['storage_name'],
                    'warehouse_id' => $storageInfo['id'],
                    'num' => $value['num'],
                    'return_id' => $data['id'],
                    'remark' => empty($value['remark'])?'':$value['remark'],
                    'shelf_id' => $shelf_id,
                    'location_id' => $location_id,
                ]);
            }
            else {
                if($value['num'] > ($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num'])) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id'],
                    'warehouse_id' => $value['warehouse_id'], 'shelf_id' => $shelf_id, 'location_id' => $location_id])
                    ->increment('num', $value['num'], [
                        'remark' => empty($value['remark'])?'':$value['remark']
                    ]);
            }

            SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id' => $data['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
            ])->increment('in_num', $value['num']);

            $info[] = [
                'goods_id' => $materielInfo['id'],
                'name' => $materielInfo['materiel_name'],
                'type_name' => $materielInfo['type_name'],
                'num' => $value['num'],
                'warehouse' => $storageInfo['storage_name'],
                'warehouse_id' => $storageInfo['id'],
                'shelf_id' => $shelf_id,
                'location_id' => $location_id,
                'serial_no' => empty($value['serial_no']) ? '' : $value['serial_no'],
            ];
        }

        return $info;
    }

    static private function materielInStorage1($paramsArr, $goodsInfo, $data)
    {
        foreach($goodsInfo as $key => $value) {
            $salesReturnInStorageInfo = SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])->first();
            $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])->first();//原始入库数量

            $materielInfo = MaterielsTypeModel::where('id', $value['materiel_type_id'])->first();
            $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

            if(empty($salesReturnInStorageInfo)) {
                if(!($value['num'] <= $salesReturnGoodsDetailInfo['num'])) {
                    return ['code' => 1, 'msg' => '超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num'], 'data' => ''];
                }

                $arr = [
                    'materiel_type_id' => $value['materiel_type_id'],
                    'name' => $materielInfo['materiel_name'],
                    'type_name' => $materielInfo['type_name'],
                    'warehouse' => $storageInfo['storage_name'],
                    'warehouse_id' => $storageInfo['id'],
                    'num' => $value['num'],
                    'return_id' => $data['id'],
                    'remark' => empty($value['remark'])?'':$value['remark'],
                ];
                SalesReturnInStorageModel::insert($arr);
            }
            else {
                if($value['num'] > ($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num'])){
                    return ['code' => 1, 'msg' => '超出可入库数量，当前可操作数量为:'.($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num']), 'data' => ''];
                }

                SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])
                    ->increment('num', $value['num'], [
                        'remark' => empty($value['remark'])?'':$value['remark']
                    ]);
            }

            SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'return_id' => $data['id']
            ])->increment('in_num', $value['num']);

            $paramsArr['content'][$key]['name'] = $materielInfo['materiel_name'];
            $paramsArr['content'][$key]['type_name'] = $materielInfo['type_name'];
            $paramsArr['content'][$key]['num'] = $value['num'];
            $paramsArr['content'][$key]['warehouse'] = $storageInfo['storage_name'];
            $paramsArr['content'][$key]['warehouse_id'] = $storageInfo['id'];
        }

        return $paramsArr;
    }


    //列表检索-有关键词
    static private function withKeyword($userId, $data)
    {
        switch($data['search_type']) {
            //1->商品名称;2->商品编号
            case 1:
            case 2:
                $result = self::searchGoodsInfo($userId, $data);
                break;
            //内部单号
            case 3:
                $result = self::searchInnerOrderNo($userId, $data);
                break;
            //外部单号
            case 4:
                $result = self::searchOutOrderNo($userId, $data);
                break;
            //快递单号
//            case 5:
//                $result = self::searchKuaidiNo($userId, $data);
//                break;
            //客户名称
            case 6:
                $result = self::searchCustomer($userId, $data);
                break;
            //司机名城
//            case 7:
//                $result = self::searchInnerOrderNo($userId, $data);
//                break;
            //收货人
            case 8:
                $result = self::searchConsignee($userId, $data);
                break;
        }

        return $result;
    }

    //列表-客户名称
    static public function searchConsignee($userId, $data)
    {
        $condition[] = ['consignee', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $salesId);
    }

    //列表-客户名称
    static public function searchCustomer($userId, $data)
    {
        $condition[] = ['customer_name', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $salesId);
    }

    //列表-快递单号搜索
//    static public function searchKuaidiNo($userId, $data)
//    {
//        $condition[] = ['order_no', 'like', '%'.$data['keyword'].'%'];
//        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);
//
//        $salesId = [];
//        foreach($salesInfo as $value) {
//            $salesId[] = $value['id'];
//        }
//
//        return self::commonSearchWithKeyword($userId, $data, $salesId);
//    }

    static private function searchOutOrderNo($userId, $data)
    {
        $condition[] = ['out_order_no', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $salesId);
    }

    static private function searchInnerOrderNo($userId, $data)
    {
        $condition[] = ['order_no', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $salesId);
    }

    static private function searchGoodsInfo($userId, $data)
    {
        $salesInfo = SalesReturnModel::select('id')->where($userId)
            ->where('repeal_status', $data['repeal_status'])
            ->from('sales_return as a')
            ->get()->toArray();

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        $condition = [];
        $condition1 = [];
        if($data['search_type'] == 1) {
            $condition[] = ['b.materiel_name', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_name', 'like', '%'.$data['keyword'].'%'];
        }
        else if($data['search_type'] == 2) {
            $condition[] = ['b.materiel_no', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_no', 'like', '%'.$data['keyword'].'%'];
        }

        $goodsDetailInfo = SalesReturnGoodsDetailModel::getGoodsDetailInfo($salesId, $condition);
        $packageContentInfo = SalesReturnPackageContentModel::getPackageContentInfo($salesId, $condition1);

        $salesIdArr = [];
        foreach($goodsDetailInfo as $value) {
            $salesIdArr[] = $value['return_id'];
        }

        //获取商品信息和套餐内商品信息的销售单id集合
        foreach($packageContentInfo as $val) {
            if(!in_array($val['return_id'], $salesIdArr)) {
                array_push($salesIdArr, $val['return_id']);
            }
        }

        return self::commonSearchWithKeyword($userId, $data, $salesIdArr);
    }

    //使用关键词检索-公共方法
    static private function commonSearchWithKeyword($userId, $data, $salesIdArr)
    {
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname'
        )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('returnMateriel', function($query) {
                $query->select(
                    'sales_return_goods_detail.id',
                    'a.materiel_name as name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img as image',
                    'price',
                    'sales_return_goods_detail.num',
                    'sales_return_goods_detail.in_num',
                    'b.storage_name as warehouse',
                    'b.id as warehouse_id',
                    'sales_return_goods_detail.materiel_type_id',
                    'sales_return_goods_detail.return_id',
                    'cost_price',
                    'return_id',
                    'sales_return_goods_detail.shelf_id',
                    'sales_return_goods_detail.location_id',
                    'a.is_product_materiel'
                )->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id');
            })
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.id',
                    'b.package_name',
                    'sales_return_package.price',
                    'sales_return_package.cost_price',
                    'sales_return_package.num',
                    'in_num',
                    'sales_return_package.return_id'
                )
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id')
                    ->with('PackageContent', function($query) {
                        $query->select(
                            'sales_return_package_content.id',
                            'sales_return_package_content.type_id',
                            'a.materiel_name',
                            'a.type_name',
                            'a.materiel_no',
                            'a.materiel_img',
                            'b.id as materiel_class_id',
                            'b.class_name',
                            'sales_return_package_content.storage_id',
                            'sales_return_package_content.num',
                            'return_package_id',
                            'sales_return_package_content.storage_manage_id',
                            'd.storage_name',
                            'd.storage_address',
                            'c.shelf_id',
                            'c.location_id'
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id');
                    });
            })
            ->where($userId)
            ->where([
                'repeal_status' => $data['repeal_status'],
                'a.delete_flag' => 0
            ]);

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        if(!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('refund_date', [$startTime, $endTime]);
        }
        else if(!empty($startTime) && empty($endTime)) {
            $query->where('refund_date', '>=', $startTime);
        }
        else if(empty($startTime) && !empty($endTime)) {
            $query->where('refund_date', '<=', $endTime);
        }

        //销售单状态
        switch($data['status']) {
            case 1://新订单
                $query->where('out_status', 0);
                $query->where('pay_status', 0);
                break;
            case 2://待退款(已收货)
                $query->where('pay_status', 0);
                $query->whereIn('out_status', [1,2]);
                break;
            case 3://待退款(已收货)
                $query->where('out_status', 0);
                $query->whereIn('pay_status', [1,2]);
                break;
            case 4:
                $query->where('out_status', 2);
                $query->where('pay_status', 2);
                break;
        }
        $query->whereIn('a.id', $salesIdArr);
        if(!empty($data['pageSize']) || !empty($data['pageSize'])){
            $query = $query->orderBy('a.id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
        }else{
            $query = $query->orderBy('a.id','desc')->get()->toArray();
        }

        foreach($query['data'] as &$value) {
            foreach($value['return_materiel'] as $k => $val) {
//                $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
//                    ->where('storage_id', $val['warehouse_id'])->first();

                $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                    ->where('storage_id', $val['warehouse_id'])->where(['shelf_id'=>$val['shelf_id'],'location_id'=>$val['location_id']])->first();

                $shelfInfo = StorageShelfModel::where('id',$val['shelf_id'])->first();
                $locationInfo = StorageShelfLocationModel::where('id',$val['location_id'])->first();
                $value['return_materiel'][$k]['shelf_name'] = $shelfInfo['shelf_name'];
                $value['return_materiel'][$k]['location_name'] = $locationInfo['location_name'];

                $value['return_materiel'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
            }
        }

        return $query;
    }

    //列表检索-无关键词
    static private function withoutKeyword($userId, $data)
    {
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname'
        )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('returnMateriel', function($query) {
                $query->select(
                    'sales_return_goods_detail.id',
                    'a.materiel_name as name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img as image',
                    'price',
                    'sales_return_goods_detail.num',
                    'sales_return_goods_detail.in_num',
                    'b.storage_name as warehouse',
                    'b.id as warehouse_id',
                    'sales_return_goods_detail.materiel_type_id',
                    'sales_return_goods_detail.return_id',
                    'cost_price',
                    'return_id',
                    'sales_return_goods_detail.shelf_id',
                    'sales_return_goods_detail.location_id',
                    'a.is_product_materiel'
                )->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id');
            })
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.id',
                    'b.package_name',
                    'sales_return_package.price',
                    'sales_return_package.cost_price',
                    'sales_return_package.num',
                    'in_num',
                    'sales_return_package.return_id'
                )
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id')
                    ->with('PackageContent', function($query) {
                        $query->select(
                            'sales_return_package_content.id',
                            'sales_return_package_content.type_id',
                            'a.materiel_name',
                            'a.type_name',
                            'a.materiel_no',
                            'a.materiel_img',
                            'b.id as materiel_class_id',
                            'b.class_name',
                            'sales_return_package_content.storage_id',
                            'sales_return_package_content.num',
                            'sales_return_package_content.storage_manage_id',
                            'return_package_id',
                            'd.storage_name',
                            'd.storage_address',
                            'c.*',

                            'c.shelf_id',
                            'c.location_id',
                            's.shelf_name',
                            'l.location_name',
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id')
                            ->leftJoin('storage_shelf as s','c.shelf_id','=','s.id')
                            ->leftJoin('storage_shelf_location as l','c.location_id','=','l.id');
                    });
            })
            ->where($userId)
            ->where([
                'repeal_status' => $data['repeal_status'],
                'a.delete_flag' => 0
            ]);
        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        if(!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('refund_date', [$startTime, $endTime]);
        }
        else if(!empty($startTime) && empty($endTime)) {
            $query->where('refund_date', '>=', $startTime);
        }
        else if(empty($startTime) && !empty($endTime)) {
            $query->where('refund_date', '<=', $endTime);
        }

        //销售单状态
        switch($data['status']) {
            case 1://新订单
                $query->where('out_status', 0);
                $query->where('pay_status', 0);
                break;
            case 2://待退款(已收货)
                $query->where('pay_status', 0);
                $query->whereIn('out_status', [1,2]);
                break;
            case 3://待退款(已收货)
                $query->where('out_status', 0);
                $query->whereIn('pay_status', [1,2]);
                break;
            case 4:
                $query->where('out_status', 2);
                $query->where('pay_status', 2);
                break;
        }
        if(!empty($data['pageSize']) || !empty($data['currentPage'])){
            $query = $query->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
        }else{
            $query = $query->orderBy('id','desc')->get()->toArray();
        }

        if(isset($query['data'])){
            foreach($query['data'] as &$value) {
                foreach($value['return_materiel'] as $k => $val) {

                    $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                        ->where('storage_id', $val['warehouse_id'])->where(['shelf_id'=>$val['shelf_id'],'location_id'=>$val['location_id']])->first();

                    $shelfInfo = StorageShelfModel::where('id',$val['shelf_id'])->first();
                    $locationInfo = StorageShelfLocationModel::where('id',$val['location_id'])->first();
                    $value['return_materiel'][$k]['shelf_name'] = $shelfInfo['shelf_name'];
                    $value['return_materiel'][$k]['location_name'] = $locationInfo['location_name'];

                    $value['return_materiel'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                }
            }
        }else{
            foreach($query as &$value) {
                foreach($value['return_materiel'] as $k => $val) {

                    $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                        ->where('storage_id', $val['warehouse_id'])->where(['shelf_id'=>$val['shelf_id'],'location_id'=>$val['location_id']])->first();

                    $shelfInfo = StorageShelfModel::where('id',$val['shelf_id'])->first();
                    $locationInfo = StorageShelfLocationModel::where('id',$val['location_id'])->first();
                    $value['return_materiel'][$k]['shelf_name'] = $shelfInfo['shelf_name'];
                    $value['return_materiel'][$k]['location_name'] = $locationInfo['location_name'];
                    $value['return_materiel'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                }
            }
        }
        return $query;
    }

    static public function payHistory($id)
    {
        if(empty(SalesReturnPayRecordModel::where('return_id', $id)->first())) {
            return '';
        }
        else {
            return SalesReturnPayRecordModel::select(
                'a.order_no',
                'b.*'
            )
                ->from('sales_return as a')
                ->leftJoin('sales_return_pay_record as b', 'a.id', '=', 'b.return_id')
                ->where('a.id', $id)
                ->get()->toArray();
        }
    }

    static public function salesReturnBatchList($typeId,$data)
    {
        return StorageManageModel::select(
            'a.id',
            'in_storage_num',
            'type_id as materiel_type_id',
            'd.materiel_name',
            'd.type_name',
            'd.materiel_no',
            'd.materiel_img',
            'a.storage_id',
            'c.storage_name',
            'b.id as batch_id',
            'b.batch_num',
            'b.batch_left_num',
            'in_storage_num',
            'b.id as batch_id',
            'b.batch_no'
        )
            ->from('storage_manage as a')
            ->leftJoin('storage_batch as b', 'a.id', '=', 'b.storage_manage_id')
            ->leftJoin('storage as c', 'c.id', '=', 'a.storage_id')
            ->leftJoin('materiel_type as d', 'd.id', '=', 'a.type_id')
            ->where('a.type_id', $typeId)
            ->distinct()
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

    }

    static public function list($userId, $data)
    {
        if(!empty($data['keyword'])) {//关键词搜索组是否启用
            $result = self::withKeyword($userId, $data);
        }
        else {
            $result = self::withoutKeyword($userId, $data);
        }

        return $result;
    }

    static public function salesReturnSerialNumber($typeId,$status,$data)
    {
        if(empty($data['product_order_id']) && empty($data['sell_id'])) {
            //从库存管理中查看序列号
            $result = self::getSerialNumberFromStorageManage($data, $status);
        }
        else {
            //退货获取所需序列号列表信息
            $result = self::salesReturnGetSerialNumber($typeId,$status,$data);
        }

        return $result;
    }

    static private function getSerialNumberFromStorageManage($data, $status)
    {
        $storageManageInfo = StorageManageModel::select(
            'a.id',
            'a.in_storage_num',
            'b.id as materiel_type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            'b.materiel_img',
            'c.id as storage_id',
            'c.storage_name',
            'b.is_product_materiel'
        )
            ->from('storage_manage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->leftJoin('storage as c', 'c.id', '=', 'a.storage_id')
            ->where('a.id', $data['storage_manage_id'])
            ->get()->toArray();

        if($storageManageInfo[0]['is_product_materiel']) {
            $productContent = MaterielProductContentModel::select(
                'a.id',
                'a.num',
                'a.type_id',
                'a.product_id',
                'b.materiel_name',
                'b.type_name',
                'b.materiel_no',
                'b.materiel_img',
                'b.is_use_serial'
            )
                ->from('materiel_product_content as a')
                ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                ->where('product_id', $storageManageInfo[0]['materiel_type_id'])
                ->get()->toArray();

            foreach($productContent as &$value) {
                $serialNumberData = SerialNumberModel::select(
                    'id as serial_id',
                    'storage_manage_id',
                    'serial_no'
                )
                    ->from('serial_number as a')
                    ->where('package_id', $storageManageInfo[0]['materiel_type_id'])
                    ->where('package_storage_id', $storageManageInfo[0]['id'])
                    ->where('goods_id', $value['type_id'])
                    ->where('status', $status)
                    ->get()->toArray();

                if(empty($serialNumberData)) {
                    $value['product_serial_list'] = [];
                }
                else {
                    $value['product_serial_list'] = $serialNumberData;
                }
            }

            $storageManageInfo[0]['product_content'] = $productContent;
            return  $storageManageInfo;
        }
        else {
            $list = StorageManageModel::select(
                'a.id',
                'a.in_storage_num',
                'b.id as materiel_type_id',
                'b.materiel_name',
                'b.type_name',
                'b.materiel_no',
                'b.materiel_img',
                'c.id as storage_id',
                'c.storage_name',
                'b.is_product_materiel',
                'd.id as serial_number_id',
                'd.serial_no'
            )
                ->from('storage_manage as a')
                ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                ->leftJoin('storage as c', 'c.id', '=', 'a.storage_id')
                ->leftJoin('serial_number as d', 'd.storage_manage_id', '=', 'a.id')
                ->where('a.id', $data['storage_manage_id'])
                ->where('d.status', $status)
                ->where('package_id', 0)
                ->get()->toArray();

            $result['current_page'] = (int)$data['currentPage'];
            $result['total'] = count($list);
            $result['next_page_url'] = count($list) > $data['pageSize']?'have something':null;
            $result['data'] = array_slice($list, --$data['currentPage'] * $data['pageSize'], $data['pageSize']);

            return $result;
        }
    }

//    static public function salesReturnSerialNumber($typeId,$status,$data)
    static public function salesReturnGetSerialNumber($typeId,$status,$data)
    {
        $keyword = !empty($data['keyword'])?$data['keyword']:"";

        $info = MaterielTypeModel::select('is_product_materiel')
            ->where('id',$typeId)->where('delete_flag',0)->first()->toArray();

        if(empty($info)) return ['code'=>1];
        $scene = isset($data['scene'])?$data['scene']:0;

        $sellIdCondition = [];
        if(!empty($data['sell_id'])) {
            $sellIdCondition['sell_id'] = ['EQ' => $data['sell_id']];
        }

        $serialArr = [];
        if($scene) {
            $productSerialNumber = ProductSlaveContentStorageModel::where('product_order_id', $data['product_order_id'])
                ->where('serial_id', '!=', 0)
                ->get()->toArray();

            foreach($productSerialNumber as $serialValue) {
                $serialArr[] = $serialValue['serial_id'];
            }
        }

        if($info['is_product_materiel'] == 1){
            $query = StorageManageModel::select(
                'a.id',
                'in_storage_num',
                'type_id',
                'type_id as materiel_type_id',
                'd.materiel_name',
                'd.type_name',
                'd.materiel_no',
                'd.materiel_img',
                'a.storage_id',
                'c.storage_name',
                'in_storage_num',
                'd.is_product_materiel'
            )
                ->from('storage_manage as a')
                ->leftJoin('storage as c', 'c.id', '=', 'a.storage_id')
                ->leftJoin('materiel_type as d', 'd.id', '=', 'a.type_id')
                ->where('d.id',$typeId)
                ->where('a.id',$data['storage_manage_id'])
                ->where('d.delete_flag',0)
                ->where('a.in_storage_num','>',0)
                ->with('productContent',function($query) use($keyword,$status){
                    $query->select('materiel_product_content.id','materiel_product_content.num','materiel_product_content.type_id',
                        'materiel_product_content.product_id','b.materiel_name','b.type_name','b.materiel_no','b.is_use_serial')
                        ->leftJoin('materiel_type as b', 'b.id', '=', 'materiel_product_content.type_id');

                });

            $list = $query->distinct()->get()/* ->paginate($data['pageSize'],['*'], '',$data['currentPage']) */->toArray();

            if(!empty($list)){
                foreach ($list as $k=>$v){

                    if(!empty($v['product_content'])){
                        foreach ($v['product_content'] as $pk=>$pv){
                            if(!empty($data['num'])){
                                $list[$k]['product_content'][$pk]['num'] = $pv['num']*$data['num'];
                            }
                            if($pv['is_use_serial'] ==1){

                                $query = SerialNumberModel::select('*')
                                    ->where('goods_id',$pv['type_id']);
                                /* ->where('package_id',$v['type_id']); */
                                if(!empty($sellIdCondition)){

                                    $query->where($sellIdCondition);
                                }
                                if($status != 88){
                                    $query -> where('status',$status);
                                }

                                $serialList = $query->where(function($query) use($keyword){
                                    $query->orWhere('serial_no', 'like', '%'.$keyword.'%');
                                })->get()->toArray();

                                if(!empty($serialList)){
                                    $packageSerialData = [];
                                    $goodsSerialData = [];
                                    foreach ($serialList as $slVal){
                                        if(($slVal['package_storage_id']>0) || ($slVal['package_id']>0)){
                                            $packageSerialData[]=[
                                                'serial_id' => $slVal['id'],
                                                'storage_manage_id' => $slVal['storage_manage_id'],
                                                'serial_no' => $slVal['serial_no']
                                            ];
                                        }else{
                                            $goodsSerialData[]=[
                                                'serial_id' => $slVal['id'],
                                                'storage_manage_id' => $slVal['storage_manage_id'],
                                                'serial_no' => $slVal['serial_no']
                                            ];
                                        }
                                    }
                                    if(!empty($packageSerialData)){
                                        $serialList = $packageSerialData;
                                    }else{
                                        $serialList = $goodsSerialData;
                                    }
                                    $list[$k]['product_content'][$pk]['product_serial_list'] = $serialList;
                                }
                            }else{
                                $list[$k]['product_content'][$pk]['product_serial_list'] = [];
                            }
                        }
                    }
                }
            }

            if(!empty($serialArr)) {
                foreach($list as $kk1 => $vv1) {
                    if(in_array($vv1['serial_number_id'], $serialArr)) {
                        unset($list[$kk1]);
                    }
                }
            }

            /*  $result['current_page'] = (int)$data['currentPage'];
             $result['total'] = count($list);
             $result['next_page_url'] = count($list) > $data['pageSize']?'have something':null;
             $result['data'] = array_slice($list, --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
         */
            return  $list;
        }else{
            DB::enableQueryLog();
            $query = StorageManageModel::select(
                'a.id',
                'in_storage_num',
                'type_id as materiel_type_id',
                'd.materiel_name',
                'd.type_name',
                'd.materiel_no',
                'd.materiel_img',
                'a.storage_id',
                'c.storage_name',
                'b.id as serial_number_id',
                'b.serial_no',
                'in_storage_num',
            )
                ->from('storage_manage as a')
                ->leftJoin('serial_number as b', 'a.id', '=', 'b.storage_manage_id')
                ->leftJoin('storage as c', 'c.id', '=', 'a.storage_id')
                ->leftJoin('materiel_type as d', 'd.id', '=', 'a.type_id')
                ->where('b.package_id', 0);
            if(!empty($sellIdCondition)){
                $query->where($sellIdCondition);
            }
            /* ->where('a.in_storage_num','>',0) */
            $query->where(function($query) use ($keyword) {
                $query->orWhere('b.serial_no', 'like', '%'.$keyword.'%');
                $query->orWhere('d.materiel_name', 'like', '%'.$keyword.'%');
            });
            if(!empty($data['storage_manage_id'])) {
                $query->where('a.id', $data['storage_manage_id']);
            }
            else {
                $query->where('a.type_id', $typeId);
            }

            if($status == 1 || $status == 0){
                $query->where('b.status',$status);
                $query->where('b.status',$status);

            }else{

                $query->whereIn('b.status',[1,0]);
            }
            /*  if($status != 0){
                 $query->where('a.in_storage_num','>',0);
             } */
            $list = $query->distinct()->get()->toArray();

            if(!empty($list)){
                foreach ($list as $k=>$v){
                    if(!empty($data['num'])){
                        $list[$k]['num'] = $data['num'];
                    }

//                        if(!empty($v['sell_id'])){
//                            $sInfo = SellModel::where(['id'=>$v['sell_id']])->first();
//                            if(!empty($sInfo) && $sInfo['out_status'] != 2){
//                                unset($list[$k]);
//                            }
//                        }
                }
            }

            if(!empty($serialArr)) {
                foreach($list as $kk1 => $vv1) {
                    if(in_array($vv1['serial_number_id'], $serialArr)) {
                        unset($list[$kk1]);
                    }
                }
            }

            $result['current_page'] = (int)$data['currentPage'];
            $result['total'] = count($list);
            $result['next_page_url'] = count($list) > $data['pageSize']?'have something':null;
            $result['data'] = array_slice($list, --$data['currentPage'] * $data['pageSize'], $data['pageSize']);

            return  $result;
        }
    }
}
